python - 裁剪X射线图像以去除黑色背景

标签 python image opencv computer-vision crop

我想从X射线中删除背景以提取实际区域。所以我原来的Original Image
图片看起来像左侧图片,我想裁剪为To be image图片。

感谢使用Python和Open-CV的解决方案。

有多个文件,因此我们不知道其高度和宽度。提前播种。因此,需要对其进行计算。

最佳答案

这是在Python / OpenCV中执行此操作的一种方法。

  • 读取输入的
  • 转换为灰色
  • 阈值
  • 将底部两行白变黑
  • 查找图像中所有白色像素的位置
  • 获取那些像素的边界
  • 在边界处裁剪图像
  • 保存结果

  • 输入:

    enter image description here
    import cv2
    import numpy as np
    
    # load image as grayscale
    img = cv2.imread('xray_chest.jpg')
    
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # threshold 
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
    hh, ww = thresh.shape
    
    # make bottom 2 rows black where they are white the full width of the image
    thresh[hh-3:hh, 0:ww] = 0
    
    # get bounds of white pixels
    white = np.where(thresh==255)
    xmin, ymin, xmax, ymax = np.min(white[1]), np.min(white[0]), np.max(white[1]), np.max(white[0])
    print(xmin,xmax,ymin,ymax)
    
    # crop the image at the bounds adding back the two blackened rows at the bottom
    crop = img[ymin:ymax+3, xmin:xmax]
    
    # save resulting masked image
    cv2.imwrite('xray_chest_thresh.jpg', thresh)
    cv2.imwrite('xray_chest_crop.jpg', crop)
    
    # display result
    cv2.imshow("thresh", thresh)
    cv2.imshow("crop", crop)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    阈值图像的底部两行被涂黑:

    enter image description here

    裁剪输入:

    enter image description here

    另一种方法是从阈值图像中获得白色区域的外部轮廓。获取轮廓的边界。然后裁剪到这些界限。

    关于python - 裁剪X射线图像以去除黑色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61986407/

    相关文章:

    python - 由于ffmpeg不可用,matplotlib动画ArtistAnimation失败

    python - 当 websocket 连接发生时, session 变量值不会更新 - Python

    .net - 调整图像大小并保留元数据/属性项

    opencv - 如何将二维笛卡尔坐标数组转换为OpenCV输入数组?

    visual-c++ - 为 Visual Studio 2012 安装 OpenCV

    python - python 连接不同类型数据的最佳实践有哪些?

    javascript - 基于变量加载图像

    JavaFx 添加图像

    opencv - 在树莓派上安装 OpenCV

    python - 如何为 "label for"设置正确的 xpath