Slicer version 4.11
I can capture a screenshot here:
or I can capture a screenshot in Script Repository here
However,both of the two methods are saving the image as .png file.If I want to see the image pixel value I have to load this image file.
So there is some way to capture a screenshot in python and make it a numpy array without saving it?
This example vtkImageDataToPNG may help. It’ll give you an array of the png compressed image by you can get something similar if you just use the vtkWindowToImageFilter output directly.
Thanks Steve! You really gave me some insight! I think I am close to the solution but maybe need a little more help!
I saw the example and did it in three steps:
def vtkImageDataToPNG(imageData):
"""
Return pngArray using the data from the vtkImageData.
"""
writer = vtk.vtkPNGWriter()
writer.SetWriteToMemory(True)
writer.SetInputData(imageData)
# use compression 0 since data transfer is faster than compressing
writer.SetCompressionLevel(0)
writer.Write()
result = writer.GetResult()
pngArray = vtk.util.numpy_support.vtk_to_numpy(result)
return pngArray
pngArray = vtkImageDataToPNG(vtk_data)
After the above three steps,I checked the type and shape of the pngArray as follows:
It seems the array has been flattened,so my next quesion is how to reshape the array to the render window size, in other words,how to get the render window size (height,width).
I compared the dimension of the pngArray with the screenshot produced by GUI:
It is strange that the two images are not the same size,in other words,the flattened numbers are different. (3714800 v.s. 3721789).Did something go wrong during the procedure of producing the pngArray?
Thank you for your continued attention and help again!
Yes, you are very close - the example I pointed to was for getting the compressed png data as an array (e.g. the data in a .png file). Instead you need to get the array from the vtkImageData that comes from the vtkWindowToImageFilter.
yeah, It seems okay because the dimensions of both images are the same.
However,when I check the value of array it is not the same,am I missing something or maybe forgot some parameters setting?
(img == image_array).all()
--> False
P.S
This image is produced by image array with your help and code:
This image is produced by screenshot capture GUI:
Apparently,the two images are different from each other,do you think I am missing some parameters?
Ah yes, I forgot that detail. It would be easier to tell if you load some data but you can see it in the gradient too: the images are mirrored vertically from each other. This is because vtk image rows go from bottom to top (like xy coordinates of a graph), while most image formats stack the rows from top to bottom (like scan lines of an old tv). So you need to rearrange the rows in memory to make the match.
Thanks a lot Steve! I have solved the problem just reversing the image array.
However it can not be done without your help,I am really grateful to your help again!