在opencv或其他软件包中是否有裁剪二值图像的功能?

2024-03-29 13:56:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现我很难在二值图像上裁剪。我不熟悉图像处理。 示例图像如下所示

原始图像:

enter image description here

所需输出(由GIMP图像编辑器手动编辑):

enter image description here

我需要通过在图像中找到一个小像素(遮罩)的边缘来裁剪图像。但是很难找到近似的边缘。请帮我弄清楚。在

提前谢谢。。!在


Tags: 图像编辑示例像素手动编辑器图像处理边缘
1条回答
网友
1楼 · 发布于 2024-03-29 13:56:08

您可以使用findContours来找到对象的边界,然后使用minAreaRect来绘制所需的输出,第一个图像。或者你可以画出物体的边界,第二张图。在

import cv2
import numpy as np

img = cv2.imread('1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_,thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)

_,contours,_ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

mask = np.zeros(img.shape)

cv2.drawContours(mask, contours, -1 , (255,255,255), 1)

rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(rect)

box = np.int0(box)
cv2.drawContours(img,[box],0,(255,255,255),1)

cv2.imshow("img",img)
cv2.imshow("mask",mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here

enter image description here

相关问题 更多 >