裁剪X射线图像以删除黑色背景

2024-03-28 20:37:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从x光片中删除背景以提取实际区域。那么我原来的Original Image 图像看起来像左边的图像,我想裁剪成To be image图像

欢迎使用Python和opencv解决方案

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


Tags: 文件图像区域宽度高度解决方案opencv背景
1条回答
网友
1楼 · 发布于 2024-03-28 20:37:08

在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

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

相关问题 更多 >