Overlay an image segmentation with numpy and matplotlib

2024/11/18 21:53:39

I am trying to overlay two images. The first one is a 512x512 NumPy array (from a CT image). The second one is also a 512x512 NumPy array but I am just interested in the pixels where the value is larger than 0 (a functional image).

To do that I am trying to create a masked array.

import numpy as np 
import numpy.ma as ma
import matplotlib.pyplot as plt# Both images are loaded from a dicom. Both are numpy arrays of (512,512) 
Image1 = readimage(path)
Image2 = readimage(path)
# Create image 2 mask
mask = ma.masked_where(Image2>0, Image2)
Image2_mask = ma.masked_array(Image2,mask)# Plot images
plt.figure(dpi=300)
y, x = np.mgrid[1:513,1:513]
plt.axes().set_aspect('equal', 'datalim')
plt.set_cmap(plt.gray())
plt.pcolormesh(x, y, Image1,cmap='gray')
plt.pcolormesh(x, y, Image2_mask,cmap='jet')
plt.axis([x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()

This code does not show any overlay. What I am doing wrong? Is there any straight way? I am coming from a Matlab environment and I am quite new to Python.

Answer

Why don't you use imshow instead?

You can plot a 2D image by doing:

plt.imshow(Image1, cmap='gray') # I would add interpolation='none'

Afterwards, you can easily overlay the segmentation by doing:

plt.imshow(Image2_mask, cmap='jet', alpha=0.5) # interpolation='none'

Changing the alpha will change the opacity of the overlay.

Additionaly, why do you create 2 masks? Only one should be enough, you can do:

Image2_mask = ma.masked_array(Image2 > 0, Image2)

Practical example:

import numpy as np
mask = np.zeros((10,10))
mask[3:-3, 3:-3] = 1 # white square in black background
im = mask + np.random.randn(10,10) * 0.01 # random image
masked = np.ma.masked_where(mask == 0, mask)import matplotlib.pyplot as plt
plt.figure()
plt.subplot(1,2,1)
plt.imshow(im, 'gray', interpolation='none')
plt.subplot(1,2,2)
plt.imshow(im, 'gray', interpolation='none')
plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)
plt.show()

enter image description here

https://en.xdnf.cn/q/26519.html

Related Q&A

Why isnt my variable set when I call the other function? [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)How can I fix a TypeError that says an operator (…

Return max of zero or value for a pandas DataFrame column

I want to replace negative values in a pandas DataFrame column with zero.Is there a more concise way to construct this expression?df[value][df[value] < 0] = 0

Getting str object has no attribute get in Django

views.pydef generate_xml(request, number):caller_id = x-x-x-xresp = twilio.twiml.Response()with resp.dial(callerId=caller_id) as r:if number and re.search([\d\(\)\- \+]+$, number):r.number(number)else:…

Cython Speed Boost vs. Usability [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

cc1plus: warning: command line option -Wstrict-prototypes is valid for Ada/C/ObjC but not for C++

I am building a C++ extension for use in Python. I am seeing this warning being generated during the compilation process - when a type:python setup.py build_ext -iWhat is causing it, and how do I fix i…

Any way to add a new line from a string with the \n character in flask?

I was playing around with flask when I came across an odd problem with the \n character. it dosent seem to have an effect in my browser, I tried putting in there but it didnt work, any ideas?from fla…

Get list of Cache Keys in Django

Im trying to understand how Django is setting keys for my views. Im wondering if theres a way to just get all the saved keys from Memcached. something like a cache.all() or something. Ive been trying t…

numpy: multiply arrays rowwise

I have those arrays:a = np.array([[1,2],[3,4],[5,6],[7,8]])b = np.array([1,2,3,4])and I want them to multiply like so:[[1*1, 2*1], [3*2, 4*2], [5*3, 6*3], [7*4, 8*4]]... basically out[i] = a[i] * b[i],…

django post_save signals on update

I am trying to set up some post_save receivers similar to the following: @receiver(post_save, sender=Game, dispatch_uid=game_updated) def game_updated(sender, **kwargs):DO SOME STUFF HEREMyPick.objects…

Fastest way to pack a list of floats into bytes in python

I have a list of say 100k floats and I want to convert it into a bytes buffer.buf = bytes() for val in floatList:buf += struct.pack(f, val) return bufThis is quite slow. How can I make it faster using …