首页 > 解决方案 > 查找矩形对象边缘的坐标

问题描述

我正在尝试使用 OpenCV 和 python 从头开始​​构建文档扫描仪应用程序。到目前为止,我已经做了以下事情:

  1. 重新缩放图像
  2. 对图像进行预处理,将其转换为灰度,应用高斯模糊,应用自适应阈值,最后使用 canny 边缘检测。
  3. 然后我找到了最大的轮廓并画了它
  4. 检测轮廓的边缘并绘制它们

第 4 步是问题所在,我在正确的位置获得了两个点,但是两个点似乎略有偏移。

我似乎无法理解我做错了什么,另外这个问题可能是由于我预处理图像的方式造成的吗?

import cv2
import numpy as np

# Function to resize the image
def Re_scaleImg(img):
    scale_percent = 50
    width = int(img.shape[1] * scale_percent / 100)
    height = int(img.shape[0] * scale_percent / 100)
    dim = (width, height)

    # resize the image
    resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    return resized


# Function to process the image
def process(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (3,3), 0)
    thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    edged = cv2.Canny(thresh, 75, 200)
    #cv2.imshow("blur", blur)
    #cv2.imshow("edged", thresh)
    return edged

# Function to find the areas of contours
def find_contourArea(contours):
    areas = []
    for cnt in contours:
        cont_area = cv2.contourArea(cnt)
        areas.append(cont_area)
    return areas


image = cv2.imread("receipt.jpeg")
resized = Re_scaleImg(image)
processed_img = process(resized)

# finding the contours
contours, hierarchy = cv2.findContours(processed_img.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
resized_copy1 = resized.copy()

# sorting the contours
sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)

largest_contour = sorted_contours[0]
epsilon = 0.01*cv2.arcLength(largest_contour, True)
approximation = cv2.approxPolyDP(largest_contour, epsilon, True)

cv2.drawContours(resized_copy1, [approximation], -1, (0, 255, 0), 3)

# Obtaining the corners of the rectangle
rot_rect = cv2.minAreaRect(largest_contour)
box = cv2.boxPoints(rot_rect)
box = np.int0(box)
for p in box:
    pt = (p[0], p[1])
    cv2.circle(resized_copy1, pt, 10, (255, 0, 0), -1)
    print(pt)

cv2.imshow("contours", resized_copy1)

cv2.waitKey(0)

两张图片如下所示:

原始图像

输出图像

标签: pythonopencvcomputer-visionopencv-pythonopencv-contour

解决方案


推荐阅读