需求:对大量同尺寸的图片需要裁剪同样区域的图片出来,采用鼠标框选范围。
# 功能:对在当前工程文件夹中的指定路劲的文件中的所有图片进行定点裁剪
# 知识点:一张图片需要裁剪出一个矩形的话只需要两个点,左上角和右下角(point1,point2 );
# 输入参数:dir_name, point1, point2 , save_dir(记得加上/)
# 所有对的图片只需要截取一部分保存,保存原来的名字即可
# 1、对dir_name中的而所有元素遍历,对于i,2、取其name暂存,3、取其值进行角点裁剪4、保存裁剪图片(save_name+2中的原图片名称)
# 2019/11/20 By liiuli in WUST
# firtst modified on 2019/11.21
import os
import cv2
global img
global point1, point2
def on_mouse(event, x, y, flags, param):
global img, point1, point2
img2 = img.copy()
if event == cv2.EVENT_LBUTTONDOWN: # 左键点击
point1 = (x, y)
cv2.circle(img2, point1, 10, (0, 255, 0), 5)
cv2.imshow('image', img2)
elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): # 按住左键拖曳
cv2.rectangle(img2, point1, (x, y), (255, 0, 0), 5)
cv2.imshow('image', img2)
elif event == cv2.EVENT_LBUTTONUP: # 左键释放
point2 = (x, y)
def cut(color_src_name,depth_src_name, point1,point2, color_save_name ,depth_save_name):
# get the 4 point of the imag
min_x = min(point1[0], point2[0])
min_y = min(point1[1], point2[1])
width = abs(point1[0] - point2[0])
height = abs(point1[1] - point2[1])
for imgname in os.listdir( color_src_name):
#print(imgname)
#read a imag
color_img = cv2.imread(color_src_name+imgname)
cut_color_img = color_img[min_y:min_y + height, min_x:min_x + width]
cv2.imwrite(color_save_name+imgname, cut_color_img)
for imgname in os.listdir( depth_src_name):
#print(imgname)
#read a imag
depth_img = cv2.imread(depth_src_name+imgname)
cut_depth_img = depth_img[min_y:min_y + height, min_x:min_x + width]
cv2.imwrite(depth_save_name+imgname, cut_depth_img)
def get_the_first_file_name(dir):
for imgname in os.listdir(dir):
# print(imgname)
# read a imag
return imgname
# try to write a function to gain autimotionaly point1 and point2 here
color_src_name = "E:\VS_project_dir\Color_depth\Project1\color/"
color_save_name = "E:\VS_project_dir\Color_depth\Project1\cutimg/"
depth_src_name ="E:\VS_project_dir\Color_depth\Project1\depth/"
depth_save_name ="E:\VS_project_dir\Color_depth\Project1\depthcut/"
# cut(color_src_name ,depth_src_name,point1,point2,color_save_name,depth_save_name);
# 在colorIMG,jpg中
def main():
global img
global point1, point2
# the first RGBimage in the dir 'color_src_name' should be showed to wait to be extract point by the mourse
img = cv2.imread(color_src_name+get_the_first_file_name(color_src_name))
cv2.namedWindow('image')
cv2.setMouseCallback('image', on_mouse)
cv2.imshow('image', img)
cv2.waitKey(0)
cut(color_src_name, depth_src_name, point1, point2, color_save_name, depth_save_name);
if __name__ == '__main__':
main()