import cv2
import numpy as np
image=cv2.imread('C:/Users/xpp/Desktop/Lena.png')
img=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(img,230,255,cv2.THRESH_BINARY_INV)
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
dot=[]
for c in contours:
#检测边界坐标
min_list=[]#保存单个轮廓的信息,x,y,w,h,area,x,y为起始点坐标
x,y,w,h=cv2.boundingRect(c)#计算点集最外面的矩形边界
min_list.append(x)
min_list.append(y)
min_list.append(w)
min_list.append(h)
min_list.append(w*h)
dot.append(min_list)
#检测最大矩形的x,y,w,h,area
max_area=dot[0][4]#把第一个矩形面积当作最大矩形面积
for inlist in dot:
area=inlist[4]
if area>=max_area:
x=inlist[0]
y=inlist[1]
w=inlist[2]
h=inlist[3]
max_area=area
#在原图上画出最大的矩形
cv2.rectangle(image,(x,y),(x+w,y+h ),(0,255,0),1)
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.resizeWindow('img',460,460)
cv2.imshow('img',image)
cv2.imwrite('C:/Users/xpp/Desktop/resut.png',image)
result=Image.open('C:/Users/xpp/Desktop/image.png')
region=result.crop((x,y,x+w,y+h))
region.save('C:/Users/xpp/Desktop/result.png')
cv2.waitKey(0)
算法:图像主体裁剪是选取图像中面积最大轮廓,绘制矩形框,裁剪目标区域。
链接:https://mp.weixin.qq.com/s?__biz=MzI0NDMyMjgxNw==&mid=2247501559&idx=1&sn=d774079b686b6c7f02e1dd186edcb8ed&chksm=e95d0199de2a888f2b4d1fa9a73eef0d9a8486051518c86675f5f76cf4598da7d337865a1a5a&token=504130470&lang=zh_CN#rd
https://mp.weixin.qq.com/s?__biz=MzI0NDMyMjgxNw==&mid=2247501569&idx=1&sn=3342c266f6265b58151fb4eba405d3e2&chksm=e95d006fde2a8979842eb6d2406b09f7d366e59feb0326e7de75ccd829e6697441f600b0732b&token=504130470&lang=zh_CN#rd
https://mp.weixin.qq.com/s?__biz=MzI0NDMyMjgxNw==&mid=2247502493&idx=1&sn=baecff5d6d5833e0422821e5b0fd26b2&chksm=e95d0df3de2a84e5e78269eafcd25a00af267b09b5e16746ee284712aa615e678e258d3ef20e&token=504130470&lang=zh_CN#rd
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!