python - 查找矩形对象边缘的坐标
问题描述
我正在尝试使用 OpenCV 和 python 从头开始构建文档扫描仪应用程序。到目前为止,我已经做了以下事情:
- 重新缩放图像
- 对图像进行预处理,将其转换为灰度,应用高斯模糊,应用自适应阈值,最后使用 canny 边缘检测。
- 然后我找到了最大的轮廓并画了它
- 检测轮廓的边缘并绘制它们
第 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)
两张图片如下所示:
解决方案
推荐阅读
- sql - 将不同的行值转换为列标题并使用 proc SQL 汇总数据
- .net-core - 如何使用 id-ecc 创建自签名证书以用于 ECDSA 签名和验证?
- firebase - 阻止 Firebase 验证手机创建帐户
- pytorch - 将 PyTorch 模型转换为 TorchScript 时出错
- typescript - 创建一个接受枚举参数的类型
- android - 如何使用智能锁解锁/登录我的应用程序
- android - 多项目 androidTest 依赖项
- c# - 如何获取编码的 url 以传递社交共享 url
- database - InfluxDB Schema 设计(又长又瘦 vs 又短又胖?
- reactjs - TypeError:无法读取未定义的属性“imageList”