【问题标题】:How to crop an image into pieces after detecting the edges using python使用python检测边缘后如何将图像裁剪成碎片
【发布时间】:2019-03-17 06:03:46
【问题描述】:

我正在处理一个破损的文档重建项目。首先,我尝试检测包含撕裂文档碎片的图像边缘,然后尝试使用示例代码通过检测到的边缘将图像裁剪成碎片,

import cv2
import numpy as np
img = cv2.imread("test.png")
img = cv2.imread("d:/test.jpeg")

cv2.imshow('Original Image',img)

new_img = cv2.Canny(img, 0, 505)
cv2.imshow('new image', new_img)

blurred = cv2.blur(new_img, (3,3))
canny = cv2.Canny(blurred, 50, 200)

## find the non-zero min-max coords of canny
pts = np.argwhere(canny>0)
y1,x1 = pts.min(axis=0)
y2,x2 = pts.max(axis=0)

## crop the region
cropped = new_img[y1:y2, x1:x2]
cv2.imwrite("cropped.png", cropped)

tagged = cv2.rectangle(new_img.copy(), (x1,y1), (x2,y2), (0,255,0), 3, cv2.LINE_AA)
cv2.imshow("tagged", tagged)
cv2.waitKey()

我的输入图像是

运行上述代码后,我得到如下输出

有人可以帮我裁剪撕裂的文档片段并将它们分配到变量中

【问题讨论】:

  • 你听说过“垃圾进垃圾出”这句话吗?如果您从光线充足且前景/背景之间具有高对比度的高质量图像开始,则问题会变得容易得多,结果质量也会高得多。

标签: python opencv image-processing


【解决方案1】:

我的工作流程的开始与您的相似。第一步:模糊图像..

blurred = cv2.GaussianBlur(gray, (5, 5), 0) # Blur

第二步:获取canny图片...

canny = cv2.Canny(blurred, 30, 150) # Canny

第三步:在 Canny 图像上绘制轮廓。这会关闭撕裂的部分。

# Find contours
_, contours, _ = cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# Draw contours on canny (this connects the contours
cv2.drawContours(canny, contours, -1, 255, 2)
canny = 255 - canny

第四步:floodfill(floodfill的区域是灰色的)

# Get mask for floodfill
h, w = thresh.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(thresh, mask, (0,0), 123);

第五步:去掉非常小和非常大的轮廓

# Create a blank image to draw on
res = np.zeros_like(src_img)
# Create a list for unconnected contours
unconnectedContours = []
for contour in contours:
    area = cv2.contourArea(contour)
    # If the contour is not really small, or really big
    if area > 123 and area < 760000:
        cv2.drawContours(res, [contour], 0, (255,255,255), cv2.FILLED)
        unconnectedContours.append(contour)

最后,一旦你分割了片段,它们就可以嵌套了。

【讨论】:

  • 嗨,我应该在变量 res @Stephen 中定义什么图像
  • @KaveeshaChethiyawardena 'res' 图像是与源图像大小相同的黑色图像。 “res”图像的唯一用途是向用户显示被认为是纸屑的轮廓。我对帖子进行了编辑以使其更清楚。
猜你喜欢
  • 2017-11-07
  • 2020-07-09
  • 2016-03-04
  • 1970-01-01
  • 2016-07-18
  • 2019-02-09
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多