gpt4 book ai didi

python - 使用 Python OpenCV 将二维码旋转到正确的位置

转载 作者:行者123 更新时间:2023-12-05 01:04:26 24 4
gpt4 key购买 nike

我是python的初学者,目前正在研究二维码检测和解码。我很难将检测到的二维码旋转到正确的位置。我已经使用 minAreaRect() 来旋转我的二维码,但它不起作用。是否有任何解决方法或正确的方法来做到这一点?谢谢!

ROI2 = cv2.imread('ROI.png')
gray2 = cv2.cvtColor(ROI2, cv2.COLOR_BGR2GRAY)
blur2 = cv2.GaussianBlur(gray2, (9, 9), 0)
thresh2 = cv2.threshold(blur2, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Morph close
# kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
# close2 = cv2.morphologyEx(thresh2, cv2.MORPH_CLOSE, kernel2, iterations=10)

# Find contours and filter for QR code
cnts2 = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts2 = cnts2[0] if len(cnts2) == 2 else cnts2[1]
c = sorted(cnts2, key=cv2.contourArea, reverse=True)[0]

draw = cv2.cvtColor(thresh2, cv2.COLOR_GRAY2BGR)
cv2.drawContours(draw, [c], 0, (0, 255, 0), 2)

rotrect = cv2.minAreaRect(c)
box = cv2.boxPoints(rotrect)
box = numpy.int0(box)
cv2.drawContours(draw, [box], 0, (0, 0, 255), 2)

cv2.imshow('thresh', thresh2)
cv2.imshow('ROI', ROI2)
cv2.imshow('minarearect', draw)

thresh ROI minAreaRect output

最佳答案

据我了解,您是在尝试歪斜图像。为此,我们需要首先计算旋转的边界框角度,然后执行线性变换。这个想法是使用 cv2.minAreaRect + cv2.warpAffine .根据文档, cv2.minAreaRect 返回

(center(x, y), (width, height), angle of rotation) = cv2.minAreaRect(...)

第三个参数为我们提供了图像歪斜所需的角度。


输入图像->输出结果

Skew angle: -39.99416732788086

代码

import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold
image = cv2.imread('2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = 255 - gray
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Compute rotated bounding box
coords = np.column_stack(np.where(thresh > 0))
angle = cv2.minAreaRect(coords)[-1]

if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
print("Skew angle: ", angle)

# Rotate image to deskew
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)

cv2.imshow('rotated', rotated)
cv2.waitKey()

注意:Python OpenCV skew correction使用投影轮廓法来纠正偏斜的另一种方法。

关于python - 使用 Python OpenCV 将二维码旋转到正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72051076/

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