如何自动裁剪此图片中灰色的白色部分?
边缘检测裁剪图片中需要的部分
我想裁剪出灰色内部的白色部分,并将其另存为数千张图片的新图片。可以通过PIL或opencv完成吗?如果可以,怎么办?图片如下所示:
我知道PIL库中有n个功能,但是如何使脚本自动在灰色中找到白色部分?白色部分有时在其中包含其他图像,有时甚至在其中包含文本。因此,在本示例中,白色部分并不总是空白的白色,也不是黑色的框架。
解决方案
这是主要思想:
- 将图像转换为灰度并模糊图像
- 执行Canny边缘检测
- 查找图像轮廓并查找每个轮廓的区域
- 过滤出最大轮廓区域并裁剪出ROI区域
卡尼边缘检测
现在,我们遍历每个轮廓并过滤出最大轮廓,该轮廓以绿色突出显示。
从边界框坐标裁剪ROI
import numpy as np
import cv2
original_image = cv2.imread("1.png")
image = original_image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)
# Find contours in the image
cnts = cv2.findContours(canny.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Obtain area for each contour
contour_sizes = [(cv2.contourArea(contour), contour) for contour in cnts]
# Find maximum contour and crop for ROI section
if len(contour_sizes) > 0:
largest_contour = max(contour_sizes, key=lambda x: x[0])[1]
x,y,w,h = cv2.boundingRect(largest_contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original_image[y:y+h, x:x+w]
cv2.imshow("ROI", ROI)
cv2.imshow("canny", canny)
cv2.imshow("detected", image)
cv2.waitKey(0)
【感谢原作者】