您的位置:首页 > 其它

中间位置裁剪固定大小图片+灰度化

2017-10-05 15:50 239 查看
'''
Created on 2017年9月14日

@author: XT
'''
import cv2
import numpy as np
import os.path
import random
import math

def rotate(
img,  #image matrix
angle #angle of rotation
):

height = img.shape[0]
width = img.shape[1]

if angle%180 == 0:
scale = 1
elif angle%90 == 0:
scale = float(max(height, width))/min(height, width)
else:
scale = math.sqrt(pow(height,2)+pow(width,2))/min(height, width)

#print 'scale %f\n' %scale

rotateMat = cv2.getRotationMatrix2D((width/2, height/2), angle, scale)
rotateImg = cv2.warpAffine(img, rotateMat, (width, height))
return rotateImg

def tfactor(img):
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV);#增加饱和度光照的噪声
hsv[:,:,0] = hsv[:,:,0]*(0.8+ np.random.random()*0.2);
hsv[:,:,1] = hsv[:,:,1]*(0.3+ np.random.random()*0.7);
hsv[:,:,2] = hsv[:,:,2]*(0.2+ np.random.random()*0.8);
img = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR);
return img

file_dir = "E:\\CarVsMicrovanVsMiniCarVsMPVVsPickupVsSUVVsTruck\\Train_Init\\"
classes = {"car"}
i = 0
for index,name in enumerate(classes):
class_path = file_dir+name+"\\"
for img_name in os.listdir(class_path):
img_pat
b7b6
h = class_path+img_name#读取每一个图片路径
image = cv2.imread(img_path)
tfimg = tfactor(image)
rotateAngle = random.randrange(0,10)
rotateImg = rotate(tfimg,rotateAngle)
H,W,Channels = tfimg.shape
y = H/2
x = W/2
winW = 136/2#目标裁剪宽的一半
winH = 36/2#目标裁剪高的一半
#         cv2.rectangle(rotateImg, (int(x-winW), int(y-winH)), (int(x + winW), int(y + winH)), (0, 255, 0), 2)
#         cv2.imshow('tfimg',rotateImg)
#         cv2.waitKey(0)
cropImg = rotateImg[int(y-winH):int(y + winH),int(x-winW):int(x + winW)]
cv2.imwrite('F:\\BaiduYunDownload\\temp\\A04_{:04d}.jpg'.format(i),cropImg)
i +=1




裁剪为灰度图片

'''
Created on 2017年10月5日

@author: XuTing
'''
import os.path
import cv2
import numpy as np

# 把彩色图像转为灰度图像
def convert2gray(img):
if len(img.shape) > 2:
gray = np.mean(img, -1)
# 上面的转法较快,正规转法如下
# r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
# gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
else:
return img

file_dir = "F:\\2345Do\\"
classes = {"StreetScene"}
i = 0
for index,name in enumerate(classes):
class_path = file_dir+name+"\\"
for img_name in os.listdir(class_path):
img_path = class_path+img_name#读取每一个图片路径
image = cv2.imread(img_path)

H,W,_ = image.shape
if W>=600 and H>=400:
y = H/2
x = W/2
winW = 600/2#目标裁剪宽的一半
winH = 400/2#目标裁剪高的一半
#cv2.rectangle(image, (int(x-winW), int(y-winH)), (int(x + winW), int(y + winH)), (0, 255, 0), 2)
#cv2.imshow('rectimage',image)
#cv2.waitKey(0)

cropImg = image[int(y-winH):int(y + winH),int(x-winW):int(x + winW)]
grayimg = convert2gray(cropImg)
cv2.imwrite('F:\\objectmarker\\neg\\streets{:08d}.jpg'.format(i),grayimg)
with open("F:\\objectmarker\\sample_neg.dat",'a',encoding='utf-8') as f:
f.write("streets{:08d}.jpg\n".format(i))
i +=1


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: