Python 如何在MRI图像中只提取大脑中央部分?

Python 如何在MRI图像中只提取大脑中央部分?,python,opencv,image-processing,deep-learning,object-detection,Python,Opencv,Image Processing,Deep Learning,Object Detection,我需要图像预处理部分的帮助。我有一张患有老年痴呆症的脑部核磁共振图像。我需要从核磁共振成像中移除头盖骨,然后切除大脑周围的所有区域。在python中如何实现这一点?与图像处理。我尝试过使用openCV,非常感谢 这是我尝试的代码: 这里是代码 def crop_brain_contour(image, plot=False): # Convert the image to grayscale, and blur it slightly gray = cv2.cvtColor(image, cv

我需要图像预处理部分的帮助。我有一张患有老年痴呆症的脑部核磁共振图像。我需要从核磁共振成像中移除头盖骨,然后切除大脑周围的所有区域。在python中如何实现这一点?与图像处理。我尝试过使用openCV,非常感谢

这是我尝试的代码:

这里是代码

def crop_brain_contour(image, plot=False):

# Convert the image to grayscale, and blur it slightly
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU)
ret, markers = cv2.connectedComponents(thresh)
marker_area = [np.sum(markers==m) for m in range(np.max(markers)) if m!=0] 
largest_component = np.argmax(marker_area)+1                       
brain_mask = markers==largest_component
brain_out = image.copy()
brain_out[brain_mask==False] = (0,0,0)

gray = cv2.GaussianBlur(gray, (5, 5), 0)

thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)

# Find contours in thresholded image, then grab the largest one
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
# extreme points
extLeft = tuple(c[c[:, :, 0].argmin()][0])
extRight = tuple(c[c[:, :, 0].argmax()][0])
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])

# crop new image out of the original image using the four extreme points (left, right, top, bottom)
new_image = image[extTop[1]:extBot[1], extLeft[0]:extRight[0]]            

return new_image
这些图像与我需要的图像相似:

当我运行此代码时,我得到了此图像


谢谢你的帮助

这里是Python/OpenCV中的一种方法

 - Read the input
 - Convert to grayscale
 - Threshold
 - Apply morphology close
 - Get the largest contour
 - Draw the largest contour as white filled on a black background as a mask
 - OPTIONALLY: erode the mask
 - Get the dimensions of the contour (after optional eroding)
 - Crop the input image and mask to those dimensions
 - Put the mask into the alpha channel of the image to make the outside transparent
 - Save the results


输入:

阈值图像:

遮罩图像:

图像的简单裁剪:

带有alpha通道的裁剪图像:

带有可选侵蚀的alpha通道的裁剪图像:


请从下一页重复和。“演示如何解决此编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后就您的算法或技术提出具体问题。我们修复坏代码。我们不会根据要求编写非平凡模型。请提供预期(MRE)。我们应该能够复制和粘贴一个连续的代码块,执行该文件,并再现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和期望的输出来测试我们的建议。显示中间结果与您预期的不同之处。@Prune我已进行了更改,并清除了问题所在!!如果你能指导我,我将是一个很大的帮助。提供一个高分辨率的图像来处理怎么样@fmw42我需要裁剪黑色区域以减少图像的噪声。它最终会给我很高的准确性
import cv2
import numpy as np

# load image
img = cv2.imread('mri.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold 
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# get external contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

# draw white filled contour on black background as mask
mask = np.zeros_like(thresh, dtype=np.uint8)
cv2.drawContours(mask, [big_contour], 0, 255, -1)

# get bounds of contour
x,y,w,h = cv2.boundingRect(big_contour)

# crop image and mask
img_crop = img[y:y+h, x:x+w]
mask_crop = mask[y:y+h, x:x+w]

# put mask in alpha channel of image
result = cv2.cvtColor(img_crop, cv2.COLOR_BGR2BGRA)
result[:,:,3] = mask_crop

# save resulting masked image
cv2.imwrite('mri_thresh.png', thresh)
cv2.imwrite('mri_cropped.png', img_crop)
cv2.imwrite('mri_cropped_alpha.png', result)

# ALTERNATE ERODE mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
thresh2 = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)

# get external contour
contours2 = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours2 = contours2[0] if len(contours2) == 2 else contours2[1]
big_contour2 = max(contours2, key=cv2.contourArea)

# draw white filled contour on black background as mask
mask2 = np.zeros_like(thresh2, dtype=np.uint8)
cv2.drawContours(mask2, [big_contour2], 0, 255, -1)

# get bounds of contour
x,y,w,h = cv2.boundingRect(big_contour2)

# crop image and mask
img_crop2 = img[y:y+h, x:x+w]
mask_crop2 = mask2[y:y+h, x:x+w]

# put mask in alpha channel of image
result2 = cv2.cvtColor(img_crop2, cv2.COLOR_BGR2BGRA)
result2[:,:,3] = mask_crop2

# save results
cv2.imwrite("mri_thresh.png", thresh)
cv2.imwrite("mri_cropped.png", img_crop)
cv2.imwrite("mri_cropped_alpha.png", result)
cv2.imwrite("mri_thresh2.png", thresh2)
cv2.imwrite("mri_cropped2.png", img_crop2)
cv2.imwrite("mri_cropped_alpha2.png", result2)

# display result
cv2.imshow("thresh", thresh)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.imshow("thresh2", thresh2)
cv2.imshow("mask2", mask2)
cv2.imshow("result2", result2)
cv2.waitKey(0)
cv2.destroyAllWindows()