首页 > 解决方案 > 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)

这是我的代码的图像和输出。我希望它的每个数字都有一个绿色轮廓。

1742.jpg

输出

标签: opencvimage-processing

解决方案


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()

那么结果是这样的 在此处输入图像描述


推荐阅读