【问题标题】:Cropping out black borders in image裁剪图像中的黑色边框
【发布时间】:2020-03-20 02:52:17
【问题描述】:

如果有办法裁剪此图像右侧和左侧的黑色部分,我需要image to crop[裁剪黑色部分的图像]。我想使用openCV,python。我有问题要裁剪出曲线。谢谢你的帮助。

https://i.stack.imgur.com/a8jt0.jpg

【问题讨论】:

  • 您不能裁剪图像的角落。但是你可以把它们变成透明的。您可以将这些区域设置为黑色,将其余区域设置为白色,并将其用作蒙版。将蒙版放入 alpha 通道,边角将是透明的。

标签: python opencv graphics computer-vision


【解决方案1】:

图像本质上是一个像素数组,所以当你说裁剪图像时,我将其翻译为从数组中删除元素。所以要从数组中删除某些元素,它的大小必须改变,而且众所周知,数组大小在 C++ 中声明后不能改变。但是,您可以过滤所需的像素并将它们复制到新数组中。我没有可用的代码,但希望下面的代码能给你一个推动

for (int i = 0; i < image.rows; i++) { 

for (int j = 0; j < image.cols; j++) { 

    if (image.at<Vec3b>(i, j)[0] != 0 && image.at<Vec3b>(i, j)[1] != 0 && image.at<Vec3b>(i, j)[2] != 0) { /*Check if all the RGB pixels are not 0 (not black)*/
        /*TODO*/
        /*MOVE THIS PIXEL TO A NEW ARRAY*/
    }
}

}

【讨论】:

    【解决方案2】:

    您不能裁剪图像的角落。但是你可以把它们变成透明的。您可以将图像转换为灰度,将这些区域设置为黑色,将其余区域设置为白色,并将其用作蒙版。将蒙版放入 alpha 通道,边角将是透明的。这是一个使用 Python/OpenCV 的示例。

    输入:

    import cv2
    import numpy as np
    
    # load image as grayscale
    img = cv2.imread('retina.jpeg')
    
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # threshold input image using otsu thresholding as mask and refine with morphology
    ret, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) 
    kernel = np.ones((9,9), np.uint8)
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
    
    # put mask into alpha channel of image
    result = img.copy()
    result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
    result[:, :, 3] = mask
    
    # save resulting masked image
    cv2.imwrite('retina_masked.png', result)
    
    # display result, though it won't show transparency
    cv2.imshow("RESULT", result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    


    【讨论】:

      猜你喜欢
      • 2013-05-18
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多