先来写一下这个代码的思路
1、先要获取切割的每一张图像在原图中的左上点的坐标和右下角的坐标(或者是裁剪后单张照片的高和宽)并且将获取的坐标放在一个列表里面,将该过程写成一个函数
2、遍历一个文件夹,分别读取每张图像,并且调用上面的函数获取坐标,利用获取的坐标进行切割。
import cv2
import numpy as np
import math
import os
def cut_img(count_w,count_h,img):
result=[]
print(img.shape)
h, w= img.shape
target_width = math.ceil(w / count_w)
target_height = math.ceil(h / count_h)
print(target_width, target_height)
count = 0
for x in range(0, count_h):
xmin = x * target_height
xmax = xmin + target_height
if (xmax > h):
xmax = h
if (x * target_height >= h):
break
for y in range(0, count_w):
ymin = y * target_width
ymax = ymin + target_width
if (ymax > w):
ymax = w
if (ymin >= w):
break
result.append([xmin,ymin,xmax,ymax])
return result
if __name__=='__main__':
path="E:\\1\\413code\\0\\"
dirs=os.listdir(path)
print(dirs)
for i in range(0,len(dirs)):
img2=cv2.imread(path+dirs[i],0)
print(img2)
result1=cut_img(4,16,img2)
print(result1)
for j in range(0, len(result1)):
xmin = result1[j][0]
ymin = result1[j][1]
xmax = result1[j][2]
ymax = result1[j][3]
print(xmin, ymin, xmax, ymax)
img1 = img2[xmin:xmax, ymin:ymax]
print(img1.shape)
cv2.imwrite("./result" + str(i) +"-" +str(j)+".png", img1)
print("ok!!!!!!")