Python OpenCV 对圆角矩形进行透视校正

标签 python python-2.7 opencv

下面的脚本(修改自 pyimagesearch.com)尝试校正扫描卡片的透视以旋转和裁剪图像。我有执行转换的最终代码,但在此之前绘制的边界矩形未按预期运行。这是原始图像:

Original

代码:

# import the necessary packages
from skimage.filters import threshold_local
import numpy as np
import cv2
import imutils

# load the image and compute the ratio of the old height
# to the new height, clone it, and resize it
image = cv2.imread('cards/red8.jpg')
ratio = image.shape[0] / 500.0
orig = image.copy()
image = imutils.resize(image, height = 500)

# convert the image to grayscale, blur it, and find edges
# in the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
blur = cv2.GaussianBlur(gray,(1,1),1000)
edged = cv2.Canny(gray, 75, 200)

# find the contours in the edged image, keeping only the
# largest ones, and initialize the screen contour
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

# loop over the contours
for c in cnts:
    # approximate the contour
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)

    # if our approximated contour has four points, then we
    # can assume that we have found our screen
    if len(approx) == 4:
        screenCnt = approx
        break

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

绘制框的输出似乎被圆角和透视校正所影响,卡住了卡片直边的微小部分。

Box

我能做些什么来获得一个适合弯曲边缘的边界矩形吗?

谢谢!

最佳答案

使用原始轮廓点而不是近似值。

if len(approx) == 4:
    screenCnt = approx
    ((x,y),(w,h),angle) = cv2.minAreaRect(c)
    rows,cols = image.shape[:2]
    M = cv2.getRotationMatrix2D((int(cols/2),int(rows/2)), angle, 1.0)
    nimg = cv2.warpAffine(image,M,(cols,rows))          
    break

result

关于Python OpenCV 对圆角矩形进行透视校正,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689127/

相关文章:

python - 如何检查 issubset 中以逗号分隔的整个单词?

python - 如何等待一个下拉列表处理完毕后再转到下一个下拉列表?

opencv - OpenCV 3 K最近

c++ - OPENCV - 直接使用指针访问过滤图像并使用内核矩阵过滤

c++ - 使用opencv编译头文件。自己的类定义

Python scikit-学习 : Why is my LinearRegression classifier's score so low?

python - 正则表达式与 Python 中的\t\n\r\f\v 不匹配

python - 如何用函数连接Pyodbc?

python - Perl 解压到 Python 转换

python-2.7 - redis 连接/管道的生命周期?