opencv - cv2.drawContours 函数无法正确绘制轮廓
问题描述
我正在尝试使用 OpenCV (4.4.0) 来绘制图像中数字的轮廓。但这对我不起作用。在我的代码下面:
# Read the input image and deskew it
im = cv2.imread('1742.jpg')
# Convert to grayscale and apply Gaussian filtering to filter noisy pixels
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (5, 5), 0)
# Threshold the image
ret, im_th = cv2.threshold(im_gray, 127, 255, cv2.THRESH_BINARY_INV)
# Find contours in the image
contours, hierarchy = cv2.findContours(im_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im_th, contours, -1, (0,255,0), 3)
cv2.imshow("Contours", im_th)
这是我的代码的图像和输出。我希望它的每个数字都有一个绿色轮廓。
解决方案
import cv2
im = cv2.imread('1742.jpg')
blur = cv2.GaussianBlur(im, (5, 5), 0)
edged = cv2.Canny(blur, 0, 150)
contours, _ = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
"""
draw a rectangle around those contours on main image
"""
[x,y,w,h] = cv2.boundingRect(contour)
cv2.rectangle(im, (x,y), (x+w,y+h), (0, 255, 0), 1)
cv2.imshow('Final Image with Contours', im)
cv2.waitKey()
cv2.imwrite('final.jpg',im)
我在 findContours 方法之前使用了 Canny 边缘检测。这是结果
如果要在数字上绘制轮廓,请使用
import cv2
im = cv2.imread('1742.jpg')
blur = cv2.GaussianBlur(im, (5, 5), 0)
edged = cv2.Canny(blur, 0, 150)
contours, _ = cv2.findContours(edged, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im, contours, -1, (0,255,0), 3)
cv2.imshow('Final Image with Contours', im)
cv2.waitKey()
推荐阅读
- oracle - 我收到错误下标超出限制。我如何解决它?
- php - 如何使空格进入文件
- javascript - 为什么我的 Ionic/Firebase 订阅被调用了 3 次?
- python - Python:线程延迟
- powershell - 尝试将绑定添加到 IIS 站点时,我返回:“配置对象是只读的”
- c# - 如何为 XML 表提供字段名称并在 datagridview 上显示?
- excel - 根据另一个表中的参数过滤结果
- strapi - 获取所有可用的语言环境,Strapi
- xcode - 如何创建键盘快捷键以在 Mac 上启动 xcode
- azure-active-directory - Microsoft 演示租户中的用户限制