I have a MR image volume in *.mhd format, and I do not have access to the original DICOM file. The image is not square and I need to crop the image and save a new *.mhd file again. I have a *.json file which contains all information of the original DICOM header.
Can anyone help me here?
Here's a example that shows how to crop an image in SimpleITK to get a square sub-image:
import random
import SimpleITK as sitk
img = sitk.Image(random.randrange(100,200), random.randrange(100,200), sitk.sitkUInt8)
size = img.GetSize()
print(size)
min_size = min(size[0], size[1])
# using python slicing to extract a sub-image
cropped_img = img[0:min_size, 0:min_size]
print(cropped_img.GetSize())
sitk.WriteImage(cropped_img, "square.mhd")
Note that the section being cropped is at the "end" (high index values) of the image.
Related
I will explain myself better, the point is that I want to develop a code that displays an image to me, then with the mouse as the image is displayed I can select or crop it as I want.
So, for example, as this code does, it would select any section of the image:
from PIL import Image
im = Image.open("test.jpg")
crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)
cropped_im.show()
That is basically it, all I want is to crop an image at the points or coordinates that I please, I have been searching but can not find any library that helps me to do so.
NOTE: The code I am showing is an answer on this post, in case you want to check it out: How can i select a part of a image using python?
EDIT: Here is something I foud that may help me in a first instance, but is not entirely what I am looking for, it at least lets me find the coordinates that I want from the image - with some modifications on the code - and then I will keep processing the image. By now it is not solving my issue but it is a beginning. --> Using "cv2.setMouseCallback" method
The comments I received from Mark Setchell and bfris enlightened me, one with a C++ code and another one with a recommendation of OpenCV.
But in addition to their comments, I found this article where they explain exactly what I want to do, so I consider my question answered. Select ROI or Multiple ROIs [Bounding box] in OPENCV python.
import cv2
import numpy as np
#image_path
img_path="image.jpeg"
#read image
img_raw = cv2.imread(img_path)
#select ROI function
roi = cv2.selectROI(img_raw)
#print rectangle points of selected roi
print(roi)
#Crop selected roi from raw image
roi_cropped = img_raw[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])]
#show cropped image
cv2.imshow("ROI", roi_cropped)
cv2.imwrite("crop.jpeg",roi_cropped)
#hold window
cv2.waitKey(0)
or
import cv2
import numpy as np
#image_path
img_path="image.jpeg"
#read image
img_raw = cv2.imread(img_path)
#select ROIs function
ROIs = cv2.selectROIs("Select Rois",img_raw)
#print rectangle points of selected roi
print(ROIs)
#Crop selected roi ffrom raw image
#counter to save image with different name
crop_number=0
#loop over every bounding box save in array "ROIs"
for rect in ROIs:
x1=rect[0]
y1=rect[1]
x2=rect[2]
y2=rect[3]
#crop roi from original image
img_crop=img_raw[y1:y1+y2,x1:x1+x2]
#show cropped image
cv2.imshow("crop"+str(crop_number),img_crop)
#save cropped image
cv2.imwrite("crop"+str(crop_number)+".jpeg",img_crop)
crop_number+=1
#hold window
cv2.waitKey(0)
I try to read a TIFF file with pillow/PIL (7.2.0) in Python (3.8.3), e.g. this image.
The resulting file seems to be corrupted:
from PIL import Image
import numpy as np
myimage = Image.open('moon.tif')
myimage.mode
# 'L'
myimage.format
# 'TIFF'
myimage.size
# (358, 537)
# so far all good, but:
np.array(myimage)
# shows only zeros in the array, likewise
np.array(myimage).sum()
# 0
It doesn't seem to be a problem of the conversion to numpy array only, since if I save it to a jpg (myimage.save('moon.jpg')) the resulting jpg image has the appropriate dimensions but is all black, too.
Where did I do wrong or is it a bug?
I am not an expert in coding but i had same problem and found the TIFF file has 4 layers. R, G ,B and Alpha. When you convert it using PIL it is black.
try to view the image as plt.imshow(myimage[:, :, 0])
you could also remove the Alpha layer by saving the read image ( i used plt.imread('image')) and then saving it as image=image[:,:,3]. Now its a RGB image.
I don't know if i answered your question, but i felt this info might be of help.
I wish to expand an image, so I can write something at the black expanded space under the original image, but it doesn't work.
I can't expand a black space and add it to the image, neither can write at a specific place
I'm new to the Pillow library, can anyone help?
You could do something like this:
read the image
create a new image (black by default) with the desired size
get data of the input image and put it down on the new one
from PIL import Image
HEIGH_OF_THE_BLACK_AREA = 100
with Image.open('image.jpg') as im:
new_im = Image.new(im.mode, size = (im.size[0], im.size[1] + HEIGH_OF_THE_BLACK_AREA))
new_im.putdata(im.getdata())
new_im.save('out.jpg')
I have a data set of images in an image processing project. I want to input an image and scan through the data set to recognize the given image. What module/ library/ approach( eg: ML) should I use to identify my image in my python- opencv code?
To find exactly the same image, you don't need any kind of ML. The image is just an array of pixels, so you can check if the array of the input image equals that of an image in your dataset.
import glob
import cv2
import numpy as np
# Read in source image (the one you want to match to others in the dataset)
source = cv2.imread('test.jpg')
# Make a list of all the images in the dataset (I assume they are images in a directory)
filelist = glob.glob(r'C:\Users\...\Images\*.JPG')
# Loop through the images, read them in and check if an image is equal to your source
for file in filelist:
img = cv2.imread(file)
if np.array_equal(source, img):
print("%s is the same image as source" %(file))
break
I have an array of pixel values from a greyscale image. I want to export these values into a text file or CSV. I have been trying to to this using various function including: xlsxwrite, write, CSV but I have so far been unsuccessful in doing this. This is what I am working with:
from PIL import Image
import numpy as np
import sys
# load the original image
img_file = Image.open("seismic.png")
img_file.show()
# get original image parameters...
width, height = img_file.size
format = img_file.format
mode = img_file.mode
# Make image Greyscale
img_grey = img_file.convert('L')
img_grey.save('result.png')
img_grey.show()
# Save Greyscale values
value = img_grey.load()
Essentially I would like to save 'value' to use elsewhere.
Instead of using the .load() method, you could use this (with 'x' as your grey-scale image):
value = np.asarray(x.getdata(),dtype=np.float64).reshape((x.size[1],x.size[0]))
This is from: Converting an RGB image to grayscale and manipulating the pixel data in python
Once you have done this, it is straightforward to save the array on file using numpy.savetxt
numpy.savetxt("img_pixels.csv", value, delimiter=',')
Note: x.load() yields an instance of a Pixel Access class which cannot be manipulated using the csv writers you mentioned. The methods available for extracting and manipulating individual pixels in a Pixel Access class can be found here: http://pillow.readthedocs.io/en/3.1.x/reference/PixelAccess.html