gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:24:45 25 4
gpt4 key购买 nike

我已经弄清楚如何使用 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

最佳答案

你可以用 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)

示例输出 enter image description here

关于Python:检测图像中的矩形边缘并将其裁剪成正方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36316205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com