我需要将目标区域给裁剪出来,要不然在后期训练网络的时候整幅图像过大,且目标区域过小,得到结果不好,还会加剧计算量。在网上找了各个大佬的博客看,没找到合适的,便自己动手写了,顺便自己的小破站刚搭建起来,记录一下自己的思路。
import cv2
"""
使用OpenCV截取图片
"""
def search(path):
left = 1024
right = 0
upper = 768
lower = 0
img = cv2.imread(path)[:,:,0]
# print(img.shape)
for i in range(768):
for j in range(1024):
if img[i,j] != 0 :
# print(img[i,j])
left = min(j,left)
right = max(j,right)
lower = max(i,lower)
upper = min(i,upper)
return (left,upper,right,lower)
def image_cut_save(path, left, upper, right, lower, save_path):
"""
所截区域图片保存
:param path: 图片路径
:param left: 区块左上角位置的像素点离图片左边界的距离
:param upper:区块左上角位置的像素点离图片上边界的距离
:param right:区块右下角位置的像素点离图片左边界的距离
:param lower:区块右下角位置的像素点离图片上边界的距离
故需满足:lower > upper、right > left
:param save_path: 所截图片保存位置
"""
img = cv2.imread(path) # 打开图像
cropped = img[upper:lower, left:right]
# 保存截取的图片
cv2.imwrite(save_path, cropped)
if __name__ == '__main__':
root_path = r'原图片的路径'
save_path = r'裁剪后的图片保存的路径'
images = os.listdir(root_path)
for image in images:
# print(image)
pic_path = os.path.join(root_path,image)
# print(pic_path)
pic_save_dir_path = os.path.join(save_path,image)
print(pic_save_dir_path)
left, upper, right, lower = search(pic_path)
# show_cut(pic_path, left, upper, right, lower)
image_cut_save(pic_path, left, upper, right, lower, pic_save_dir_path)
到此这篇关于python opencv实现目标区域裁剪功能的文章就介绍到这了,更多相关python opencv区域裁剪内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!