【问题标题】:Python: Detecting Rect of Edges In Image & Cropping It Into a Square?Python:检测图像中的边缘矩形并将其裁剪成正方形?
【发布时间】:2016-07-18 21:24:13
【问题描述】:

我已经弄清楚如何使用 PIL 检测图像中的边缘(图像大多是带有黑色绘图标记的白色背景)。如何检测包含这些边缘的矩形,以便裁剪图像。

例如,我想裁剪如下内容:

进入:

或者这个:

进入:

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

更新:

我已通过执行以下操作设法检测到边缘:

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

如何获得包含所有这些边的矩形?

【问题讨论】:

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

标签: python image opencv python-imaging-library


【解决方案1】:

你可以做到这一点,例如使用 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(遇到问题),但如果你能评论你的代码就好了:) 我会尽快测试一下。
  • openCV 是否通过 boundingRect 调用返回矩形的宽度和高度或右下角坐标?如果它是宽度和高度而不是坐标,则上面的代码将不起作用 - 以一种非常糟糕的方式。如果是坐标,你可以将它们命名为 x1, y1, x2, y2 而不是 x, y, w, h。
  • @jsbueno boundingRect 返回左上角坐标和矩形宽度和高度。为什么它不起作用?
  • @jsbueno 对面的cv2.rectangle 取左上角和右下角坐标,所以右下角我们可以通过计算x+w, y+h得到
  • 因为你正在使用 "max" 并传递 "w" 和 "h" - 如果你只是将 "..., x + w, y + h)" 传递给调用最大以上。
猜你喜欢
  • 2018-01-27
  • 2017-07-30
  • 2013-02-16
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多