如何在Python中检测边缘并裁剪图像 [英] How to detect edge and crop an image in Python

查看:1310
本文介绍了如何在Python中检测边缘并裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Image Processing in Python and I'm trying to solve a common problem. I have an image having a signature of a person. I want to find the edges and crop it to fit the signature in the image.

我尝试了Canny Edge Detection,并使用一系列使用PIL,CV2的解决方案(文章和答案)裁剪图像,但是似乎没有任何效果.我正在寻找一个可行的解决方案.

I tried Canny Edge Detection and cropping the image using a list of existing solutions (articles & answers) using PIL, CV2, but none seem to work. I'm looking for a working solution.

我尝试过的一些解决方案:

Some solutions I tried:

  1. 在边缘检测后从各个方向裁剪图像

    如何裁剪出最大的矩形图片

    还有更多...尽管看起来很简单,但是没有任何工作.使用任何现有解决方案时,我都遇到错误或无法预期的输出.

    and many more... None worked although seems very simple. I encountered either errors or not expected output using any of the existing solutions.

    推荐答案

    您需要的是阈值化.在OpenCV中,您可以使用 .

    What you need is thresholding. In OpenCV you can accomplish this using cv2.threshold().

    我开枪了.我的方法如下:

    I took a shot at it. My approach was the following:

    1. 转换为灰度
    2. 阈值图像仅获得签名而没有其他内容
    3. 查找那些在阈值图像中显示的像素
    4. 以原始灰度围绕该区域
    5. 从作物中创建一个新的阈值图像,显示效果不严格

    这是我的尝试,我认为效果很好.

    Here was my attempt, I think it worked pretty well.

    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)
    

    结果如下:

    这篇关于如何在Python中检测边缘并裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆