python - opencv 锐界提取图像

标签 python numpy opencv image-processing

我能够提取两个图像之间的差异(边缘不清晰的原始图像)。我想要做的是将图像转换为具有锐利四边形边缘的图像(中间步骤到最终图像)。 我正在使用带有 cv2 和 numpy 的 python 2.7。我现在的主要问题是,我不知道如何对其进行编程以生成最终图像(因此如何切割不清晰的边缘并生成具有锐边的最终图像)。

请问,如何进行这种图像处理?

原始图像 enter image description here

中间步骤enter image description here

最终图像 enter image description here

附加图片: enter image description here enter image description here enter image description here

最佳答案

首先我们找到平滑的轮廓,然后我们使用 approxPolyDP 将其拉直成四边形:

import cv2
import numpy as np

img = cv2.imread(r'c:\TEMP\so57564249.jpg')

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold and shrink mask
_, thresh = cv2.threshold(img_gray, 10, 255, cv2.THRESH_BINARY)
thresh = cv2.erode(thresh, np.ones((10,10), np.uint8), iterations=1)

# find countour
contours,_ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]

# straighten contour to quadrilateral
epsilon = 0.001*cv2.arcLength(cnt,True)
while True:
   epsilon += epsilon
   approx = cv2.approxPolyDP(cnt,epsilon,True)
   if len(approx) <= 4:
       break

# output
thresh[:,:] = 0
thresh = cv2.fillPoly(thresh, [approx], 255)
img = cv2.bitwise_and(img, img, mask=thresh)
cv2.polylines(img, [approx], True, (0,255,0), 2)

enter image description here

选择 10 的内核大小来去除图像的模糊边缘或多或少是随意的。您可能需要调整它。为了可视化它的效果,您可以添加

cv2.polylines(img, [cnt], True, (0,0,255))

在最后一行之后绘制初始阈值图像的平滑轮廓。

关于python - opencv 锐界提取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564249/

相关文章:

python - 如何对 numpy 数组中的特定数字选择进行舍入?

Python:如何在包级帮助菜单中嵌入所有文档字符串帮助?

java - 使用 Opencv Android 实现分水岭分割时出错

python - 循环浏览目录并将所有面孔保存在其他目录中

python - NumPy - 使用强度值矩阵的图像(矩阵)阈值处理。

python - 按时间戳合并 Pandas 数据帧

python - Gensim入门错误: No such file or directory: 'vectors.bin'

python - gpxpy 未在 to_xml() 中输出扩展名

python - Django迁移错误: TypeError expected string or bytes-like object

python - "Converting"Numpy 数组到 Matlab,反之亦然