Python:如何检测图像边缘的矩形并将其裁剪成正方形?

5
我已经学会了使用PIL在图像中检测边缘(图像大多数是白色背景和黑色绘画标记)。如何检测包含这些边缘的矩形,以便我可以裁剪图像。
例如,我想裁剪类似这样的东西:

enter image description here

转换为:

enter image description here

或者这个:

enter image description here

转换为:

enter image description here

我熟悉PIL中的裁剪,但不知道如何自动围绕对象居中。

更新:

我通过以下方式成功检测到边缘:

from PIL import Image, ImageFilter
image = Image.open("myImage.png")
image = image.filter(ImageFilter.FIND_EDGES)

我该如何获取包含所有这些边缘的矩形?

enter image description here


哦,那应该很困难。你怎么知道这个“关键特性”在哪里?不过这很有趣。 - ForceBru
哦,关于关键特性,我指的是任何标记(在上面的示例中是整个数字3),它会尝试裁剪它,以便所有标记都适合新的裁剪图像中。 - KingPolygon
1个回答

4
你可以使用OpenCV来完成这个任务。
import cv2

#Load the image in black and white (0 - b/w, 1 - color).
img = cv2.imread('input.png', 0)

#Get the height and width of the image.
h, w = img.shape[:2]

#Invert the image to be white on black for compatibility with findContours function.
imgray = 255 - img
#Binarize the image and call it thresh.
ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)

#Find all the contours in thresh. In your case the 3 and the additional strike
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
#Calculate bounding rectangles for each contour.
rects = [cv2.boundingRect(cnt) for cnt in contours]

#Calculate the combined bounding rectangle points.
top_x = min([x for (x, y, w, h) in rects])
top_y = min([y for (x, y, w, h) in rects])
bottom_x = max([x+w for (x, y, w, h) in rects])
bottom_y = max([y+h for (x, y, w, h) in rects])

#Draw the rectangle on the image
out = cv2.rectangle(img, (top_x, top_y), (bottom_x, bottom_y), (0, 255, 0), 2)
#Save it as out.jpg
cv2.imwrite('out.jpg', img)

示例输出在此输入图片描述


我还没有安装OpenCV(遇到了麻烦),但如果您能评论您的代码,那会很好 :) 我会尽快尝试测试它。 - KingPolygon
openCV的boundingRect调用返回矩形的宽度和高度还是右下角坐标?如果是宽度和高度而不是坐标,上面的代码将以非常错误的方式工作。如果是坐标,您可以将它们命名为x1、y1、x2、y2,而不是x、y、w、h。 - jsbueno
@jsbueno boundingRect 返回左上角坐标和矩形的宽度和高度。为什么它不起作用? - vitalii
@jsbueno 相反,cv2.rectangle 接受左上角和右下角坐标,因此我们可以通过计算 x+w, y+h 来获取右下角。 - vitalii
因为你正在取"max"并传递"w"和"h" - 如果你只是将"...,x + w,y + h)"传递给上面的max调用,它就会起作用。 - jsbueno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接