I would like to remove CT bed from the image. Basically I would want to remove everything below the red line in this image and subsequent ones (i would fill with 0 zeros or something)
Is there a way to get the location of the highest non zero number on the y-axis? Or the height of longest horizontal non zero number? Then I could just replace all values below with zero. Or is there a better way to do this? Thanks!
I get the image data from
df = pydicom.dcmread(img)
plt.imshow(df.pixel_array, vmax=dicom_max_pixel)
plt.show()
IIUC, have a look at the following minimal example:
First, we're importing the modules.
import matplotlib.pyplot as plt
import numpy as np
Creating an example image, 1
representing the bed.
image = np.zeros((10, 10))
image[6, 2:8] = image[7, 4:6] = 1
print(image)
plt.imshow(image)
plt.show()
It prints and shows:
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 1. 1. 1. 1. 1. 0. 0.]
[0. 0. 0. 0. 1. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
We use np.all
to find out for each line if it is all zeros. Afterwards, we use np.where
to get the index of the first False
.
zero_lines = np.all(image == 0, axis=1)
first_false = np.where(zero_lines == False)[0][0]
print(zero_lines)
print(first_false)
This prints:
[ True True True True True True False False True True]
6
We use this information to crop the image accordingly.
image = image[:first_false]
print(image)
plt.imshow(image)
plt.show()
It prints and shows:
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]