Working with .tiff images in python for deep learning - python

I am currently working on a project using imaging flow cytometry images in python. the images are .tiff an example file name is image27_Ch1.ome.tiff . I am having a little trouble with opening these images. I have tried to use matplotlib and PIL and the tifffile library but whatever I try does not seem to work. It always tells me FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/zacha/Desktop/cell_images/27_Ch1.ome.tiff' . Although I double and triple-checked that the directory to the image is correct, even when I copy and paste the path to the image from the image properties itself it still gives me this error. I tried converting a few images into .png images and the code works and will load the images, this is not ideal because I have a data set of a few hundred thousand images. I was wondering if anyone out there in the StackOverflow universe knows how to deal with a problem like this or has dealt with .tiff images in python in the past. Below is some of the code that I have tried to open these images.
import matplotlib.pyplot as plt
path = 'C:/Users/zacha/Desktop/cell_images/27_Ch1.ome.tiff'
I = plt.imread(path)
from PIL import Image
path = 'C:/Users/zacha/Desktop/cell_images/27_Ch1.ome.tiff'
image = Image.open(path)
Thank you very much to whoever reads or answers this question.

Try rasterio and matplotlib
import rasterio
import matplotlib.pyplot as plt
src_path = "Your_sat_img.tif"
img = rasterio.open(src_path)
plt.figure(figsize=(22, 22))
plt.imshow(img.read([1,2,3]).transpose(1, 2, 0))

You can try this code to open any tiff file:
import rasterio
from rasterio.plot import show
tiff_img = rasterio.open('filename.tif')
show(tiff_img)

Related

iterating blob count for all the images in a folder using Python

I have been writing a program to count the particles present in a image using the scikit-image library, and on its own it works great. The problem arises when I try to iterate such detection for all the images in a folder, to hopefully then have a average of the detected particles between all the images taken. I tried using os, but it always gave the same error:
File ~\anaconda3\lib\site-packages\imageio\core\request.py:260 in _parse_uri
raise FileNotFoundError("No such file: '%s'" % fn)
FileNotFoundError: No such file: 'C:\thesis\2022-07-18\150ms_6Hz_0000.bmp'
I have tried looking online for help, but all I could find was not helpful in my situation.
Here is the code I have for now. It is clearly very simple, but I don't have much experience with programming and this is the best I could do for now
import os
import numpy as np
from skimage import data
from skimage.io import imread
from skimage.feature import blob_dog, blob_log, blob_doh
import matplotlib.pyplot as plt
img_number = len(next(os.walk("C:/thesis/2022-07-18/500 ug/"))[2])
for images in os.listdir(r'C:\thesis\2022-07-18\50 ug'):
blob_count = imread(images)
average_blob_count = len(blob_count)/img_number
print (average_blob_count)
Thanks for the help!

Showing all the images with matplotlib

I'm using numpy and matplotlib to read all the images in the folder for image processing techniques. Although, I have done the part of reading image dataset from folders and process it with numpy array. But the problem, I'm facing is of showing all the images with matplotlib.imshow function. Everytime I want to show all the images with imshow function, unfortunately it just give me first image nothing else.
My code is below:
import os
import numpy as np
import matplotlib.pyplot as mpplot
import matplotlib.image as mpimg
images = []
path = "../path/to/folder"
for root, _, files in os.walk(path):
current_directory_path = os.path.abspath(root)
for f in files:
name, ext = os.path.splitext(f)
if ext == ".jpg":
current_image_path = os.path.join(current_directory_path,f)
current_image = mpimg.imread(current_image_path)
images.append(current_image)
for img in images:
print len(img.shape)
i = 0
for i in range(len(img.shape)):
mpplot.imshow(img)
mpplot.show()
I will be thankful if somebody can help me in this.
P.S. I'm pretty new with python, numpy and also at stackoverflow. So, please don't mind if the question is unclear or not direct.
Thanks,
About showing only one plot in one moment: please get familiar with matplotlib subplots.
Also, what is your problem that you are not iterating over images. You are calling img x-times.
Try to iterate over images as below:
for img in images:
mpplot.imshow(img)
mpplot.show()
I think what you need to add is mpplot.figure() before each mpplot.show(), this will open a new window for each image.

Get information of multipage tiff image (I;16) with python

I am working with images from a multispectral camera and after doing some processing I have 16 bits multipage image with 6 bands in tiff format. Now, I need to get information of each layer through python code, so I used:
from __future__ import division
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
files = os.listdir('my directory')
for file in files:
I = Image.open(os.path.join('my directory', "image.tif"))
plt.imshow(np.asarray(I))
plt.show()
print (I.size, I.mode, I.format)
band1 = np.asarray(I,dtype=np.uint16)
A = np.asarray(I,dtype=np.float32)
I can read the image but I cannot find the information of the six different layers and actually, I am not sure from which band the values of "A" are. The image is too big to upload it, but I can try to share it if it´s necessary. Thanks.

Reading image using Pillow fails in Jupyter notebook

I'm trying to read a jpg file using Pillow (Version 3.2.0) in Jupyter notebook (Python 3.4), but it fails with the following error:
OSError: broken data stream when reading image file
I'm using the following code:
from PIL import Image
im = Image.open("/path/to/image.jpeg")
im.show()
It works fine both in the interactive Python shell and using Python 2.7 instead of 3.4.
I've followed these steps already: Using Pillow with Python 3
Anyone an idea what's going on?
Looks like you're not pointing to the directory where your photo is stored.
import os
defaultWd = os.getcwd()
defaultWd # Sets your curretn wd
os.chdir(defaultWd + '\\Desktop') # Points to your photo--e.g., on Desktop
os.getcwd() # Shows change in wd
from PIL import Image
im = Image.open("Mew.jpg")
im.show() # Will plot to your default image viewing software
And another way if you don't want to change current wd:
im = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
im.show()
And if you want to plot inline:
from matplotlib.pyplot import imshow
%matplotlib inline
inlinePic = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
imshow(inlinePic)
Note: You may also want to simply try typing 'jpg' instead of 'jpeg' as you did above, if your image is in your current working directory. Also, if PIC is not installed, you'll get this error NameError: name 'Image' is not defined.
The problem was related to another import: I was importing Tensorflow before PIL, which caused the problem. Same issue as this one: https://github.com/scikit-image/scikit-image/issues/2000. Changing the order of the imports solved it.

Using python to save a JPG image that was edited in the script

Referring to the answer to this question, I tried to save my own JPG image files, after some basic image processing. I've only applied a rotation and a shear. This is my code:
import numpy as np
import sys
from skimage import data, io, filter, color, exposure
import skimage.transform as tf
from skimage.transform import rotate, setup, AffineTransform
from PIL import Image
mypath = PATH_TO_FILENAME
readfile = FILENAME
img = color.rgb2gray(io.imread(mypath + readfile))
myimg = rotate(img, angle=10, order=2)
afine_tf = tf.AffineTransform(shear=0.1)
editedimg = tf.warp(myimg, afine_tf)
# IF I UNCOMMENT THE TWO LINES BELOW, I CAN SEE THE EDITED IMAGE AS EXPECTED
#io.imshow(editedimg)
#io.show()
saveimg= np.array(editedimg)
result = Image.fromarray((saveimg).astype(np.uint8))
newfile = "edited_" + readfile
result.save(path+newfile)
I know that the image processing was fine because if I display it before saving, it's just the original image with a bit of rotation and shearing, as expected. But I'm doing something wrong while saving it. I tried without the astype(np.uint8)) part but got an error. Then I removed some of the code from the link mentioned above because I guessed it was particularly for Fourier Transforms, since when I included some of their code, then I got an image that was all gray but with white lines in the direction of the shear I'd applied. But now the image that gets saved is just 2KB of nothing but blackness.
And when I tried something as simple as:
result = Image.fromarray(editedimg)
result.save(path+newfile)
then I got this error:
raise IOError("cannot write mode %s as JPEG" % im.mode)
IOError: cannot write mode F as JPEG
I don't really need to use PIL, if there's another way to simply save my image, I'm fine with that.
Look into the PIL fork, Pillow, is is not as outdated and what you should probably be using for this.
Also depending on your operating system you may need a few other libraries to compile PIL with JPEG support properly, see here
This may also help Says you need to convert your image to RGB mode before saving.
Image.open('old.jpeg').convert('RGB').save('new.jpeg')

Categories