我是Python的图像处理新手,我正在尝试解决一个常见问题。我的图像上有一个人的签名。我想找到边缘并裁剪它以适合图像中的签名。
我尝试了Canny Edge Detection并使用PIL,CV2使用现有解决方案(文章和答案)列表裁剪图像,但似乎都没有。我正在寻找一个有效的解决方案。
我尝试了一些解决方案:
还有更多......虽然看起来非常简单但没有工作。我使用任何现有的解决方案都遇到了错误或预期的输出。
答案 0 :(得分:21)
您需要的是阈值处理。在OpenCV中,您可以使用cv2.threshold()
完成此操作。
这是我的尝试,我认为它运作得很好。
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)