如何在python中填充连接边的轮廓并裁剪图像?
如何在python中填充连接边的轮廓并裁剪图像?,python,opencv,image-preprocessing,Python,Opencv,Image Preprocessing,左侧是原始图像,我使用了canny边缘检测方法仅获取图像的外部边缘,正如您从右侧图像中看到的那样。现在可以用白色填充连接的边并裁剪图像了吗?很抱歉,我是图像处理方面的新手如果您提供单独的图像,则始终是最佳选择 在Python/OpenCV中有一种方法可以做到这一点 将图像读取为灰度 门槛 应用形态学关闭 获取一个外部轮廓 获取轮廓的边界框坐标 在黑色背景上绘制填充的白色轮廓 裁切结果 保存结果 输入: 阈值图像: 填充轮廓图像: 裁剪图像: 使用填充轮廓的替代方法是对内部进行整体
左侧是原始图像,我使用了canny边缘检测方法仅获取图像的外部边缘,正如您从右侧图像中看到的那样。现在可以用白色填充连接的边并裁剪图像了吗?很抱歉,我是图像处理方面的新手如果您提供单独的图像,则始终是最佳选择 在Python/OpenCV中有一种方法可以做到这一点
- 将图像读取为灰度
- 门槛
- 应用形态学关闭
- 获取一个外部轮廓
- 获取轮廓的边界框坐标
- 在黑色背景上绘制填充的白色轮廓
- 裁切结果
- 保存结果
输入:
阈值图像: 填充轮廓图像: 裁剪图像:
使用填充轮廓的替代方法是对内部进行整体填充。hi fmw42。谢谢你的详细解释。这是一个非常准确的答案。你为什么不投票接受这个答案呢?
import cv2
import numpy as np
# load image
img = cv2.imread("outline.png", cv2.IMREAD_GRAYSCALE)
# threshold
thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]
# apply close morphology
#kernel = np.ones((5,5), np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# get bounding box coordinates from the one filled external contour
filled = np.zeros_like(thresh)
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
the_contour = contours[0]
x,y,w,h = cv2.boundingRect(the_contour)
cv2.drawContours(filled, [the_contour], 0, 255, -1)
# crop filled contour image
result = filled.copy()
result = result[y:y+h, x:x+w]
# write result to disk
cv2.imwrite("outline_thresh.png", thresh)
cv2.imwrite("outline_filled.png", filled)
cv2.imwrite("outline_cropped.png", result)
# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("FILLED", filled)
cv2.imshow("CROPPED", result)
cv2.waitKey(0)
cv2.destroyAllWindows()