OpenCV从图像中检索形状轮廓并进行变换

2024-10-02 18:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用OpenCV和python检索图像的矩形部分(文档、护照照片或类似的东西)。它可以工作,但不是对每个图像都有效,并在以下代码块中失败,错误为axis = normalize_axis_index(axis, nd) numpy.core._internal.AxisError: axis 1 is out of bounds for array of dimension 1

for cnt in contours:
    perimeter = cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, 0.03 * perimeter, True)
    if (len(approx) == 4 and
            cv2.isContourConvex(approx) and
            maxAreaFound < cv2.contourArea(approx) < MAX_COUNTOUR_AREA):
        maxAreaFound = cv2.contourArea(approx)
        pageContour = approx

原始图像 original

脱粒 thresh

边缘 enter image description here

完整代码:

^{pr2}$

为什么会这样?在


Tags: andof代码图像trueforcv2opencv
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:39
import cv2

img = cv2.imread('img.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (40, 0, 80), (255, 255, 255))  # set to the color you want to detect

blur = cv2.blur(mask, (5, 5))

ret, thresh = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cnt = contours[0]
cnts = cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

cv2.imshow('blur', blur)
cv2.imshow('thresh', thresh)
cv2.imshow('cnts', cnts)

cv2.waitKey(0)

result

或者只是在图像中保存。。在

相关问题 更多 >