我们可以使用opencv的函数加上python代码的编写对单个图片进行任意倍数的分割。
直接开始:
首先导入Opencv库
import cv2
然后我们设置分割的倍数
cut_row
= 5
cut_col
= 5
接下来读取图片(换成你要处理的图片路径)
original_image
= cv2
.imread
(r
'.\路径\xxx.png')
获取图片尺寸
cutting_step_row
= row
/cut_row
cutting_step_col
= col
/cut_col
cutting_row
= row
/cut_row
cutting_col
= col
/cut_col
index
= 1
进行处理(记得更换路径)
for i
in range(cut_row
):
for j
in range(cut_col
):
print('i=', i
)
print('j=', j
)
y0
= 0 + j
* cutting_step_col
y1
= cutting_col
+ j
* cutting_step_col
x0
= 0 + i
* cutting_step_row
x1
= cutting_row
+ i
* cutting_step_row
cropped
= original_image
[int(y0
):int(y1
), int(x0
):int(x1
)]
if index
< 10:
cv2
.imwrite
('\路径\'
+ str(index
) + ".jpg", cropped
)
index
= index
+ 1
elif index
< 100:
cv2
.imwrite
('\路径\'
+ str(index
) + ".jpg", cropped
)
index
= index
+ 1
结果展示
原图:
处理以后的结果(分割为9份):
处理以后的结果(分割为25份):
整体代码(记得修改路径)
import cv2
cut_row
= 5
cut_col
= 5
original_image
= cv2
.imread
(r
'C:\Users\Administrator\Desktop\fg\yt\0002.png')
row
, col
, cha
= original_image
.shape
print('row=', row
)
print('col=', col
)
print('cha=', cha
)
cutting_step_row
= row
/cut_row
cutting_step_col
= col
/cut_col
cutting_row
= row
/cut_row
cutting_col
= col
/cut_col
index
= 1
for i
in range(cut_row
):
for j
in range(cut_col
):
print('i=', i
)
print('j=', j
)
y0
= 0 + j
* cutting_step_col
y1
= cutting_col
+ j
* cutting_step_col
x0
= 0 + i
* cutting_step_row
x1
= cutting_row
+ i
* cutting_step_row
cropped
= original_image
[int(y0
):int(y1
), int(x0
):int(x1
)]
if index
< 10:
cv2
.imwrite
('C:\\Users\\Administrator\\Desktop\\fg\\before\\000' + str(index
) + ".jpg", cropped
)
index
= index
+ 1
elif index
< 100:
cv2
.imwrite
('C:\\Users\\Administrator\\Desktop\\fg\\before\\00' + str(index
) + ".jpg", cropped
)
index
= index
+ 1
转载请注明原文地址:https://ipadbbs.8miu.com/read-10205.html