How to convert multiple mha images to nii - python

I would like to convert about 300 .mha images into .nii format. Which are under subfolders . I have successfully converted one image but in order to go each folder and convert, its a tidious task. Please suggest me code that is functioning with sitk library
import SimpleITK as sitk
import matplotlib.pyplot as plt
import numpy as np
import os
OUTPUT_DIR = '/home/user/Downloads/'
Image = sitk.ReadImage('Input dir')
print(Image.GetPixelIDTypeAsString())
sitk.WriteImage(Image, os.path.join(OUTPUT_DIR, 'Flair.nii'))

Use python's os.walk method to get all the files in a directory tree. Then select out only the ones with the '.mha' suffix.
Here's an example of how it works:
https://www.tutorialspoint.com/python/os_walk.htm
Or you can try and decipher the os library documentation:
https://docs.python.org/3/library/os.html

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!

Working with .tiff images in python for deep learning

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)

How to read images using csv in python

I have a csv file that contains three columns namely (image file names, labels(in form of 0,1...), and class names). While another folder contains all the images. I want to read the images using this csv file and use them further for the task of image classification using deep learning models on python.
You can try this:
import pandas as pd
import cv2
import numpy as np
from pathlib import Path
df = pd.read_csv('path_to_csv.csv')
path = Path('path/to/img/dir') # relative path is OK
dataset = df.apply(lambda file_name, label:
return (cv2.imread(path/file_name), label),
axis=1)
dataset = np.asarray(dataset)
Now you'll have dataset that is a numpy matrix with images as column 1 and labels as column 2
I'm using OpenCV to import image. Of course you can use others like pillow too, but OpenCV is faster than pillow

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.

tifffile in Python not writing 16bit tiff

I had a look for duplicates but I'm not sure similar questions had the answer...
I'm using tifffile in Python to read a multipage tiff (16 bit), take the first channel page/channel, blur it and save it as a 16 bit tiff.
import os
import matplotlib.pyplot as plt
import tifffile as tiff
from scipy import misc
tiff_list = []
for i in files_list[0]:
tiff_list.append(tiff.imread('/filepath_to_tiff_folder/'+i))
blurred_list = []
for i in tiff_list:
blurred_list.append(ndimage.gaussian_filter(i[0], sigma=3))
for i,v in enumerate(blurred_list):
misc.imsave('/filepath/testblur2/'+str(files_list[0][i])+'_Brightfield_Blur.tif', v)
Here, files_list is just a list of the file names of the tiffs.
The above code works absolutely fine for blurring and saving the tiff, but it saves it as 8 bit instead.
Is there something in the above I can add to keep it 16 bit or do I have to use another method?
You are using scipy, not tifffile, to save the images.
Use tifffile.imsave to save 16-bit images, e.g.:
from glob import glob
from scipy import ndimage
from tifffile import imread, imsave
for filename in glob('*.tif'):
i = imread(filename)
i = ndimage.gaussian_filter(i[0], sigma=3)
imsave('blurred_' + filename, i)

Categories