gpt4 book ai didi

python-3.x - 矩形,使用python3,opencv3进行轮廓检测

转载 作者:行者123 更新时间:2023-12-02 17:35:50 25 4
gpt4 key购买 nike

我想从图像中检测纸张。我应用了meanBlur,Canny,扩张,阈值等算法来查找。我能够找到工作表,但不知道如何裁剪矩形并应用变换

答题卡

这是我的代码

import numpy as np
import cv2

image = cv2.imread('im_1.jpg')
image = cv2.resize(image, (800, 600))
draw = np.zeros_like(image)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thresh = cv2.erode(thresh, kernel, iterations=4)
thresh = cv2.dilate(thresh, kernel, iterations=4)
im, cnts, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

max_area = -1
max_c = 0
for i in range(len(cnts)):
contour = cnts[i]
area = cv2.contourArea(contour)
if (area > max_area):
max_area = area
max_c = i

contour = cnts[max_c]


rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)



cv2.drawContours(image, [box],-1, (0, 255, 0), 2)

cv2.imshow('Sheet', image)

cv2.waitKey(0)
cv2.destroyAllWindows()

代码结果:
结果

最佳答案

您的方法存在一些小缺陷。以下代码会有所帮助。我也提到了所做的更改。

代码:

import numpy as np
import cv2

image = cv2.imread('C:/Users/Jackson/Desktop/score.jpg')

#--- Resized the image to half its dimension maintaining the aspect ratio ---
image = cv2.resize(image, (0, 0), fx = 0.5, fy = 0.5)
draw = np.zeros_like(image)

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

#--- I found the inverse binary image, because contours are found for objects in white. Since the border of the page is in black you have to invert the binary image. This is where it went wrong.
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

#--- I did not perform any morphological operation ---
im, cnts, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

max_area = -1
max_c = 0
for i in range(len(cnts)):
contour = cnts[i]
area = cv2.contourArea(contour)
if (area > max_area):
max_area = area
max_c = i

contour = cnts[max_c]


rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)

cv2.drawContours(image, [box],-1, (0, 255, 0), 2)

cv2.imshow('Sheet', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

enter image description here

关于python-3.x - 矩形,使用python3,opencv3进行轮廓检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51125741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com