对内境图片裁剪,去除黑边,效果如下图所示
原图
标出矩形框
结果
import cv2
import os
def main01():
root = "C:\\Users\\liuminggui\\Desktop\\rename\\all\\" # 图片来源路径
save_path = "C:\\Users\\liuminggui\\Desktop\\rename\\save\\" # 图片修改后的保存路径
images = os.listdir(root)
for i in images:
path = root + i
print(i)
x,y,w,h=rect_crop(path) # 得到要裁剪的,左上角坐标(x,y)和宽度w,高度h
image=cv2.imread(root+i)
cv2.imwrite(save_path+i, image[y:y+h+1,x:x+w+1]) # 保存裁剪图片
def rect_crop(root=r'F:\Project\DenseBox\data\000001.jpg'):
img = cv2.imread(root)
# img = cv2.pyrDown(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 得到灰度图
x_,y_ = gray.shape
ret,thresh = cv2.threshold(gray,50,255,cv2.THRESH_BINARY) # 测试得到50比较好
# 注意opencv2和3这个函数可能有2个或者三个返回值
img111,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contours: # 遍历所有轮廓
print(c)
x,y,w,h = cv2.boundingRect(c)
if w * h > x_ * y_ * 0.33: # 轮廓大于整个面积的1/3,应该就是我们要找的
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
print(x,y,w,h)
cv2.imshow('img+rectangle',img)
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
return (x,y,w,h)
return (0,0,0,0) # 找不到大矩形轮廓,则返回默认值0
if __name__ == '__main__':
# main1()
# liuminggui()
main01()
cover from YSH and sloan
评论区