Kin*_*gon 5 python opencv image python-imaging-library
我已经想出了如何使用 PIL 检测图像中的边缘(图像主要是带有黑色绘图标记的白色背景)。如何检测包含这些边缘的矩形,以便裁剪图像。
例如,我想裁剪这样的东西:
进入:
或这个:
进入:
我熟悉 PIL 中的裁剪,但我不知道如何围绕对象自动居中。
我设法通过执行以下操作来检测边缘:
from PIL import Image, ImageFilter
image = Image.open("myImage.png")
image = image.filter(ImageFilter.FIND_EDGES)
Run Code Online (Sandbox Code Playgroud)
我如何获得包含所有这些边的矩形?
小智 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4538 次 |
| 最近记录: |