如何在Python中检测边缘并裁剪图像

2024-04-30 04:29:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python中的图像处理新手,我正在尝试解决一个常见的问题。我有一张有人签名的照片。我想找到边缘并裁剪它以适合图像中的签名。

输入图像

enter image description here

预期产量

enter image description here

我尝试了精明的边缘检测,并使用现有的解决方案列表(文章和答案)使用PIL,CV2裁剪图像,但似乎没有一个工作。我在找一个可行的解决方案。

我尝试了一些解决方案:

  1. https://www.quora.com/How-can-I-detect-an-object-from-static-image-and-crop-it-from-the-image-using-openCV

  2. Crop Image from all sides after edge detection

  3. How to crop biggest rectangle out of an image

还有更多。。。虽然看起来很简单,但没有一个成功。我在使用任何现有解决方案时遇到错误或不期望输出。


Tags: 答案from图像cropimagean列表文章
1条回答
网友
1楼 · 发布于 2024-04-30 04:29:04

你需要的是阈值。在OpenCV中,您可以使用^{}来实现这一点。

我试过了。我的方法如下:

  1. 转换为灰度
  2. 对图像设置阈值以仅获取签名而不获取其他内容
  3. 查找阈值图像中显示的像素的位置
  4. 在原始灰度中围绕该区域裁剪
  5. 从对显示没有那么严格的裁剪创建新的阈值图像

这是我的尝试,我觉得效果很好。

import cv2
import numpy as np

# load image
img = cv2.imread('image.jpg') 
rsz_img = cv2.resize(img, None, fx=0.25, fy=0.25) # resize since image is huge
gray = cv2.cvtColor(rsz_img, cv2.COLOR_BGR2GRAY) # convert to grayscale

# threshold to get just the signature
retval, thresh_gray = cv2.threshold(gray, thresh=100, maxval=255, type=cv2.THRESH_BINARY)

# find where the signature is and make a cropped region
points = np.argwhere(thresh_gray==0) # find where the black pixels are
points = np.fliplr(points) # store them in x,y coordinates instead of row,col indices
x, y, w, h = cv2.boundingRect(points) # create a rectangle around those points
x, y, w, h = x-10, y-10, w+20, h+20 # make the box a little bigger
crop = gray[y:y+h, x:x+w] # create a cropped region of the gray image

# get the thresholded crop
retval, thresh_crop = cv2.threshold(crop, thresh=200, maxval=255, type=cv2.THRESH_BINARY)

# display
cv2.imshow("Cropped and thresholded image", thresh_crop) 
cv2.waitKey(0)

结果是:Cropped signature with thresholding

相关问题 更多 >