imread_collection() Load Patterns (scikit-images Python) - python

I am having an issue (likely my own mistake) using imread_collection() to load a set of 480 .tif images from a folder.
I have an external drive with 480 images in it such that the path name for each image is:
'D:\img_channel000_position000_time000000000_z000.tif',
'D:\img_channel000_position000_time000000001_z000.tif',
'D:\img_channel000_position000_time000000002_z000.tif'
and so on. The 480 images are the only objects on the external drive. I know this is the path name as I have successfully used
import skimage
from skimage import io
image = skimage.io.imread('D:\img_channel000_position000_time000000000_z000.tif')
to import an image and perform a first-pass at the analysis I was looking to accomplish. I, perhaps naively, then attempted to use the following code to import the entirety of the collection
import skimage
from skimage import io
ic = skimage.io.imread_collection('D:\*.tif')
However, the variable ic is never even created. The code runs successfully without error, but nothing occurs. Is this a problem with how I have implemented the load pattern? I have also tried the more complete D:\img_channel000_position000_*_z000.tif, but nothing occurred. Any advice would be greatly appreciated!

The issue might be, as #Juan pointed out in the comments, that Linux and Windows use different directory separators. One possible way to make your code platform-independent would be using os.path.join like this:
In [18]: import os
In [19]: from skimage import io
In [20]: external_drive = 'D:'
In [21]: file_spec = '*.tif'
In [22]: load_pattern = os.path.join(external_drive, file_spec)
In [23]: ic = io.imread_collection(load_pattern)
In [24]: ic
Out[24]: <skimage.io.collection.ImageCollection at 0x1f94f27f080>
In [25]: ic.files
Out[25]: ['D:\\img_001.tif', 'D:\\img_002.tif', 'D:\\img_003.tif']
Test performed on a machine with Windows 10 and Python 3.6.3 (Anaconda).

Related

OpenCV displays 'None' for a large number of images

I am trying to run a pre-trained pose detection model on a new dataset.
When I pass a single image to the model, I get the correct results.
Although, when I apply a for loop for multiple images present in a folder(as shown below), openCV even fails to load half of the images.
Keep in mind I am running this code on Intel i3 dual core laptop.
import os
import cv2
DIR="C:\\Name_of_Folder\\"
for i in os.listdir(DIR):
image=cv2.imread(i)
print(image,i)
Output:
None frame_000000.jpg
None frame_000001.jpg
None frame_000002.jpg
None frame_000003.jpg
os.listdir() does not return absolute file paths, but only the file names.
import os
import cv2
DIR="C:\\Name_of_Folder\\"
for i in os.listdir(DIR):
image=cv2.imread(os.path.join(DIR, i))
print(image,i)
The path you're trying to use to read image is wrong. You have to use:
import cv2
import os
DIR="C:\\Name_of_Folder\\"
for i in os.listdir(DIR):
image=cv2.imread(os.path.join(DIR,i))
print(image,i)

pydicom is not defined

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.

Why geotiff could not be opened by gdal?

I'm newbie in python and in geoprocessing. I'm writing some program to calculate ndwi. To make this, I try to open geotiff dataset with gdal, but dataset can't be opened. I tried to open different tiff files (Landsat8 multiple data, Landsat7 composite, etc), but dataset is always None.
What reason to this could be? Or how can i find it out?
Here's a part of code:
import sys, os, struct
import gdal, gdalconst
from gdalconst import *
import numpy as np
from numpy import *
class GDALCalcNDWI ():
def calcNDWI(self, outFilePath):
gdal.AllRegister()
# this allows GDAL to throw Python Exceptions
gdal.UseExceptions()
filePath = "C:\\Users\\Daria\\Desktop.TIF\\170028-2007-05-21.tif"
# Open
dataset = gdal.Open(filePath, gdal.GA_ReadOnly)
# Check
if dataset is None:
print ("can't open tiff file")
sys.exit(-1)
Thanks
Whenever you have a well-known file reader that is returning None, make sure the path to your file is correct. I doubt you have a directory called Desktop.TIF, I'm assuming you just made a typo in your source code. You probably want C:\\Users\\Dara\\Desktop\\TIF\\170028-2007-05-21.tif as the path (note that Desktop.TIF ==> Desktop\\TIF).
The safest thing to do is right click on the file, go to properties, and copy/paste that path into your python source code.

Python troubles

I've been trying to throw together a python program that will align, crop and create an RGB image from HST and VLA .fits data. Unfortunately I've run into a bit of a problem with it continually opening a past file that does not exist in the folder and neither is it opening in the code itself. I've googled and googled and haven't found anything like it, so perhaps it's just common sense to most, but I can't figure it out. Here's the error message:
You can see at the top that the program I'm running has the filename rgbhstvla.py. I'm not sure what the error message means. Here's the python program as well:
import pyfits
import numpy as np
import pylab as py
import img_scale
from pyraf import iraf as ir
fits.open('3c68.fits', readonly)
j_img = pyfits.getdata('230UVIS.fits')
h_img = pyfits.getdata('230IR.fits')
k_img = pyfits.getdata('5GHZ.fits')
jmin,jmax = j_img.mean()+0.75*j_img.std(),j_img.mean()+5*j_img.std()
hmin,hmax = h_img.mean()+0.75*h_img.std(),h_img.mean()+5*h_img.std()
kmin,kmax = k_img.mean()+0.75*k_img.std(),k_img.mean()+5*k_img.std()
img = numpy.zeros((1024,1024,3))
img[:,:,0] = img_scale.asinh(j_img,scale_min=jmin,scale_max=jmax)
img[:,:,1] = img_scale.asinh(h_img,scale_min=hmin,scale_max=hmax)
img[:,:,2] = img_scale.asinh(k_img,scale_min=kmin,scale_max=kmax)
pylab.clf()
pylab.imshow(img)
pylab.show()
(I'm still working on the program since I'm new to python, tips here would be nice as well but they're mostly unnecessary as I'm sure I'll figure it out eventually).
Python cannot find the file 3c68.fits, which is expected to be in the current working directory, C:\Users\Brandon\Desktop\Research. Either make sure the file is in that directory, or provide an absolute path in your code.

python opencv imwrite ... can't find params

I am using opencv with python. I wanted to do an cv2.imwrte:
cv2.imwrite('myimage.png', my_im)
The only problem is that opencv does not recognize the params constants:
cv2.imwrite('myimage.png', my_im, cv2.CV_IMWRITE_PNG_COMPRESSION, 0)
It cannot find CV_IMWRITE_PNG_COMPRESSION at all. Any ideas?
I can't find key CV_XXXXX in the cv2 module:
Try cv2.XXXXX
Failing that, use cv2.cv.CV_XXXXX
In your case, cv2.cv.CV_IMWRITE_PNG_COMPRESSION.
More info.
The docs for OpenCV (cv2 interface) are a bit confusing.
Usually parameters that look like CV_XXXX are actually cv2.XXXX.
I use the following to search for the relevant cv2 constant name. Say I was looking for CV_MORPH_DILATE. I'll search for any constant with MORPH in it:
import cv2
nms = dir(cv2) # list of everything in the cv2 module
[m for m in nms if 'MORPH' in m]
# ['MORPH_BLACKHAT', 'MORPH_CLOSE', 'MORPH_CROSS', 'MORPH_DILATE',
# 'MORPH_ELLIPSE', 'MORPH_ERODE', 'MORPH_GRADIENT', 'MORPH_OPEN',
# 'MORPH_RECT', 'MORPH_TOPHAT']
From this I see that MORPH_DILATE is what I'm looking for.
However, sometimes the constants have not been moved from the cv interface to the cv2 interface yet.
In that case, you can find them under cv2.cv.CV_XXXX.
So, I looked for IMWRITE_PNG_COMPRESSION for you and couldn't find it (under cv2....), and so I looked under cv2.cv.CV_IMWRITE_PNG_COMPRESSION, and hey presto! It's there:
>>> cv2.cv.CV_IMWRITE_PNG_COMPRESSION
16
Expanding on mathematical.coffee to ignore case and look in both namespaces:
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 = 'imwrite'
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]
>>>
in cv2
['imwrite']
in cv
['CV_IMWRITE_JPEG_QUALITY', 'CV_IMWRITE_PNG_COMPRESSION', 'CV_IMWRITE_PXM_BINARY']
>>>
Hopefully this problem will go away in some later release of cv2...
the compression style is automatically chosen from the file extension. see the cv2.imwrite help here.
however you might still be interested to know all the possible flags used by all the possible functions in cv2 and cv modules.
look for cv2.txt and cv.txt on your computer. they will be where the opencv modules are installed. at the bottom of those text files are a list of the flags used by the respective modules.
just in case you don't find them, you can download the ones i have from here, though they are from august 2011:
cv2.txt
cv.txt
in fact, with cv2 style API, this constant is replaced with cv2.IMWRITE_PNG_COMPRESSION.

Categories