I'm trying to learn how to use pydicom for reading and processing dicom images. I'm using Python 3.
import dicom
import numpy
ds = pydicom.read_file(lstFilesDCM[0])
print(ds.pixel_array)`
I get an error NameError: name 'pydicom' is not defined. If I change
ds = pydicom.read_file(lstFilesDCM[0])
to
ds = dicom.read_file(lstFilesDCM[0])
(using dicom.read_file instead), I get the following error:
NotImplementedError: Pixel Data is compressed in a format
pydicom does not yet handle. Cannot return array
I also verified that pydicom is properly installed and updated.
How do i fix this?
You are trying to call a class that you have not imported before:
Use:
import pydicom
import numpy
ds = pydicom.read_file(lstFilesDCM[0])
print(ds.pixel_array)
or
import dicom
ds = dicom.read_file("the_name_of_file.dcm")
Documentation: http://pydicom.readthedocs.io/en/stable/pydicom_user_guide.html
If you want to get your hands on the pixel data, I suggest to use the convert program from the ImageMagick suite. You can either call this program from Python using the subprocess module. (See this example, where I convert them to JPEG format), or you can use one of the Python bindings.
If you want to manipulate the images, using the bindings might be preferable. But note that not all the bindings have been converted to ImageMagick version 7.
Related
Is there a way in Python or any other language to convert .raw/mhd image data to Nifti/nii?
I can load the .raw/mhd file in python via SimpleITK as in this post:
Reading *.mhd/*.raw format in python
import skimage.io as io
img = io.imread('file.mhd', plugin='simpleitk')
I am having a hard time exporting as nii with proper dimensions... would ideally use the header information in the original mhd file...
Thanks
You should be able to just do in with SimpleITK. You would do something like this:
import SimpleITK as sitk
img = sitk.ReadImage("input.mhd")
sitk.WriteImage(img, "output.nii")
If you don't have SimpleITK in python, installing it as follows:
pip install SimpleITK
SimpleITK does its best effort of preserving all header information, although it's not perfect. Hopefully the voxel dimensions will be preserved.
I am using Python 2.7.11 and OpenCV 2.4.9. I cannot read a video by using cv2.imread() or cv2.VideoCapture().
import cv2
cap = cv2.VideoCapture('cam.avi')
print ("open = ",cap.isOpened())
OR
import cv2
cap = cv2.imread('cam.avi')
print ("open = ",cap.isOpened())
It will return false.
I don't know why. I am sure that the cam.avi is here.
imread() does not support reading from video files directly.
See also the documentation of OpenCV.
If you want to read a video with imread you will first have to convert it to single images, either via a serperate program (ffmpeg comes to mind) or using OpenCV and store the images in memory.
Try providing full path to video, like:
import cv2
cap = cv2.VideoCapture(r'C:\Users\e01069\Downloads\drop.avi')
print ("open = ",cap.isOpened())
If you run following in your same file, you would know that python is looking for your file on some different location.
import os
print os.path.abspath(__file__) #this is your current working directory
Note: .imread wouldn't work this way.
I'm trying to open Image file from PyFileSystem MemoryFS using PIL, I tried to do that like this example and i got the error below:
from PIL import Image
from fs.memoryfs import MemoryFS
fs=MemoryFS()
fs.makedir("test")
out=fs.open("test/file.jpg",'wb')
out.write(someimagefile.read())
out.close()
in=fs.open("test/file.jpg",'rb')
im=Image.open(in) #error: cannot identify image file <IO wrapper for <MemoryFile in <MemoryFS> test/file.jpg>>
however if I don't use a directory (ex. out=fs.open("file.jpg",'wb')) It does work as expected.
What am I doing wrong?
Thanks for your help.
I already get an error using the following line:
from fs.memoryfs import MemoryFS
Probably I don't have that library installed. Do you need this library? You can just open the image without opening it with MemoryFS:
im = Image.open("test/file.jpg")
Side note: I wouldn't use in as variable name, since it is also a Python keyword.
I've looked around and read the docs, and found no way or solution, so I ask here. Is there any packages available to use Python to convert a JPG image to a PNG image?
You could always use the Python Image Library (PIL) for this purpose. There might be other packages/libraries too, but I've used this before to convert between formats.
This works with Python 2.7 under Windows (Python Imaging Library 1.1.7 for Python 2.7), I'm using it with 2.7.1 and 2.7.2
from PIL import Image
im = Image.open('Foto.jpg')
im.save('Foto.png')
Note your original question didn't mention the version of Python or the OS you are using. That may make a difference of course :)
Python Image Library: http://www.pythonware.com/products/pil/
From: http://effbot.org/imagingbook/image.htm
import Image
im = Image.open("file.png")
im.save("file.jpg", "JPEG")
save
im.save(outfile, options...)
im.save(outfile, format, options...)
Saves the image under the given filename. If format is omitted, the
format is determined from the filename extension, if possible. This
method returns None.
Keyword options can be used to provide additional instructions to the
writer. If a writer doesn't recognise an option, it is silently
ignored. The available options are described later in this handbook.
You can use a file object instead of a filename. In this case, you
must always specify the format. The file object must implement the
seek, tell, and write methods, and be opened in binary mode.
If the save fails, for some reason, the method will raise an exception
(usually an IOError exception). If this happens, the method may have
created the file, and may have written data to it. It's up to your
application to remove incomplete files, if necessary.
As I searched for a quick converter of files in a single directory, I wanted to share this short snippet that converts any file in the current directory into .png or whatever target you specify.
from PIL import Image
from os import listdir
from os.path import splitext
target_directory = '.'
target = '.png'
for file in listdir(target_directory):
filename, extension = splitext(file)
try:
if extension not in ['.py', target]:
im = Image.open(filename + extension)
im.save(filename + target)
except OSError:
print('Cannot convert %s' % file)
from glob import glob
import cv2
pngs = glob('./*.png')
for j in pngs:
img = cv2.imread(j)
cv2.imwrite(j[:-3] + 'jpg', img)
this url: https://gist.github.com/qingswu/1a58c9d66dfc0a6aaac45528bbe01b82
import cv2
image =cv2.imread("test_image.jpg", 1)
cv2.imwrite("test_image.png", image)
I don't use python myself, but try looking into:
http://www.pythonware.com/products/pil/
import Image
im = Image.open("infile.png")
im.save("outfile.jpg")
(taken from http://mail.python.org/pipermail/python-list/2001-April/700256.html )
I checked the documentation but its incomplete: there is no mention of what rtype parameter actually is.
I think it's a reduce type but I can't find any of variables like cv2.CV_REDUCE_SUM etc... I found this problem with many function that use different variable names. What's the best way to find proper names in cv2 API?
I found out that the appropriate variable can be found in the following package
cv2.cv
If you use CV_REDUCE_SUM operator on uint8 image you have to explicitly provide dtype parameter of bigger range to avoid overflowing (e.g.
slice = cv2.reduce(image, 1, cv2.cv.CV_REDUCE_SUM, dtype=numpy.int32)
If you use CV_REDUCE_AVG operation, result can't overflow that's why setting dtype is optional.
There are some omisions in the current new cv2 lib. Typically these are constants that did not get migrated to cv2 yet and are still in cv only. Here is some code to help you find them:
import cv2
import cv2.cv as cv
nms = [(n.lower(), n) for n in dir(cv)] # list of everything in the cv module
nms2 = [(n.lower(), n) for n in dir(cv2)] # list of everything in the cv2 module
search = 'window'
print "in cv2\n ",[m[1] for m in nms2 if m[0].find(search.lower())>-1]
print "in cv\n ",[m[1] for m in nms if m[0].find(search.lower())>-1]
If you're finding this while using Open CV 3.x or later, these constants have been renamed to cv2.REDUCE_SUM, cv2.REDUCE_AVG, cv2.REDUCE_MAX, and cv2.REDUCE_MIN.
An example of the working reduce function:
reducedArray = cv2.reduce(im, 0, cv2.REDUCE_MAX)
GitHub issue for documentation