首页 > 解决方案 > 删除附加到图像边框的元素

问题描述

我正在使用 OpenCV 使用图像处理来检测胸部 X 光片中的肺炎,所以我需要删除图像边界的附加区域以仅获取肺部,有人可以帮我在 python 中编码吗?

此图像解释了应用此方法后我想要此图像的内容:调整大小、直方图均衡、otsu 阈值和逆二进制阈值、形态过程(打开然后关闭)

这是原始图像原始图像

标签: pythonopencvimage-processingdetection

解决方案


这就是我在 Python/OpenCV 中解决问题的方法。在四周添加一个白色边框,用黑色填充以替换白色,然后删除多余的边框。

输入:

在此处输入图像描述


import cv2
import numpy as np

# read image
img = cv2.imread('lungs.jpg')
h, w = img.shape[:2]

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# add 1 pixel white border all around
pad = cv2.copyMakeBorder(gray, 1,1,1,1, cv2.BORDER_CONSTANT, value=255)
h, w = pad.shape

# create zeros mask 2 pixels larger in each dimension
mask = np.zeros([h + 2, w + 2], np.uint8)

# floodfill outer white border with black
img_floodfill = cv2.floodFill(pad, mask, (0,0), 0, (5), (0), flags=8)[1]

# remove border
img_floodfill = img_floodfill[1:h-1, 1:w-1]    

# save cropped image
cv2.imwrite('lungs_floodfilled.png',img_floodfill)

# show the images
cv2.imshow("img_floodfill", img_floodfill)
cv2.waitKey(0)
cv2.destroyAllWindows()

在此处输入图像描述


推荐阅读