【问题标题】:Crop X-Ray Image to Remove black background裁剪 X 射线图像以移除黑色背景
【发布时间】:2020-05-24 13:05:22
【问题描述】:

我想从 X 射线中移除背景以提取实际区域。所以我原来的 图片看起来像左图,我想裁剪成 图像。

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

有多个文件,所以我们不知道高度和宽度。提前收割。所以需要计算。

【问题讨论】:

  • 尝试运行 Numpy 的 np.sum(axis=0) 对每列中的像素求和...或查看许多其他类似的问题。

标签: python image opencv computer-vision crop


【解决方案1】:

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

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


输入:

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()


底部两行变黑的阈值图像:

裁剪输入:

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

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 2018-07-01
    • 2019-07-19
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多