Python Code Image Stitching not working - Mac M1 - python-3.x

so a friend of mine sent me this code that worked for him to stitch images together vertically. However, when I try to run it, it gives me this:
Traceback (most recent call last):
File "/Users/usr/Downloads/Test/Concat.py", line 15, in <module>
final = Image.new('RGB', (images[0].width, totalHeight))
IndexError: list index out of range
How can I resolve this?
Here's my code:
import os
from PIL import Image
from os import listdir
from os.path import isfile
files = [f for f in listdir() if isfile(f)]
images = []
totalHeight = 0
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
images.append(Image.open(file))
totalHeight += images[-1].height
final = Image.new('RGB', (images[0].width, totalHeight))
runningHeight = 0
for im in images:
final.paste(im, (0, runningHeight))
runningHeight += im.height
final.save("Concat.png")
Thanks in advance.

Related

How to read an image using imread?

I am trying to add gui to my deep learning project based on cnn..
So on clicking classify button ,I need to read an image and send the same to the same prediction function for futher processing. Kindly help me here. I have just shared the part of the code.
def sample_prediction(test_im):
feed_dict_test = {
x: test_im.reshape(1, img_size_flat),
y_true: np.array([[2,1,0]])
}
test_pred = session.run(y_pred_cls, feed_dict=feed_dict_test)
return classes[test_pred[0]]
def classify(file_path):
global label_packed
image = Image.open(file_path)
#image = image.resize((30,30))
#image = numpy.expand_dims(image, axis=0)
#image = numpy.array(image)
#cv2.imshow("frame",inputface)
#inputface = cv2.resize(inputface, (img_size, img_size), cv2.INTER_LINEAR) / 255
pred =sample_prediction(image)
sign = classes[pred+1]
print(sign)
def show_classify_button(file_path):
classify_b=Button(top,text="Classify X-ray Image",command=lambda: classify(file_path),padx=10,pady=5)
classify_b.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
classify_b.place(relx=0.79,rely=0.46)
label.configure(foreground='#011638', text=sign)
When I run this,Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\DELL\anaconda3\envs\Pneu Packages\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "cnn_train_test.py", line 489, in <lambda>
classify_b=Button(top,text="Classify X-ray Image",command=lambda: classify(file_path),padx=10,pady=5)
File "cnn_train_test.py", line 482, in classify
pred =sample_prediction(image)
File "cnn_train_test.py", line 372, in sample_prediction
x: test_im.reshape(1, img_size_flat),
AttributeError: 'JpegImageFile' object has no attribute 'reshape'
You can read, write and process images as Numpy arrays or PIL Images and you can move between the two types as you go. Be aware that OpenCV uses BGR ordering, while PIL and most other packages assume RGB.
So, you can read your image into a Numpy array with OpenCV:
import cv2
# Load a file into a Numpy array - "na" will be BGR order
na = cv2.imread('image.png', cv2.IMREAD_COLOR)
And write that Numpy array to disk with OpenCV using:
import cv2
# Write Numpy array to disk as image - "na" must be BGR order
cv2.imwrite('result.jpg', na)
Or you can use PIL to load your image as a PIL Image:
from PIL import Image
# Load a file into a "PIL Image"
pi = Image.open('input.jpg')
And write that Image to disk with PIL:
from PIL import Image
# Save PIL Image to disk
pi.save('result.png')
You can convert a PIL Image to a Numpy array like this:
# Make Numpy array from PIL Image
na = np.array(pi)
And convert a Numpy array to a PIL Image like this:
# Make PIL Image from Numpy array
pi = Image.fromarray(na)
Bear in mind the channel ordering and potentially use this to re-order the channels:
BGRarray = cv2.cvtColor(RGBarray, cv2.COLOR_RGB2BGR)
or
RGBarray = cv2.cvtColor(BGRarray, cv2.COLOR_BGR2RGB)

Trying to print image count

I am new to Python and I am trying to start CNN for one project. I mounted the gdrive and I am trying to download images from the gdrive directory. After, I am trying to count the images that I have in that directory. Here is my code:
import pathlib
dataset_dir = "content/drive/My Drive/Species_Samples"
data_dir = tf.keras.utils.get_file('Species_Samples', origin=dataset_dir, untar=True)
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir('*/*.png')))
print(image_count)
However, I get the following error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-78-e5d9409807d9> in <module>()
----> 1 image_count = len(list(data_dir('*/*.png')))
2 print(image_count)
TypeError: 'PosixPath' object is not callable
Can you help, please?
After suggestion, my code looks like this:
import pathlib
data_dir = pathlib.Path("content/drive/My Drive/Species_Samples/")
count = len(list(data_dir.rglob("*.png")))
print(count)
You are trying to glob files you need to use one of the glob methods that pathlib has:
import pathlib
data_dir = pathlib.Path("/path/to/dir/")
count = len(list(data_dir.rglob("*.png")))
In this case .rglob is a recursive glob.

Decompress nifti medical image in gz format using python

I want to decompress a butch of nii.gz files in python so that they could be processed in sitk later on. When I decompress a single file manually by right-clicking the file and choosing 'Extract..', this file is then correctly interpreted by sitk (I do sitk.ReadImage(unzipped)). But when I try to decompress it in python using following code:
with gzip.open(segmentation_zipped, "rb") as f:
bindata = f.read()
segmentation_unzipped = os.path.join(segmentation_zipped.replace(".gz", ""))
with gzip.open(segmentation_unzipped, "wb") as f:
f.write(bindata)
I get error when sitk tries to read the file:
RuntimeError: Exception thrown in SimpleITK ReadImage: C:\d\VS14-Win64-pkg\SimpleITK\Code\IO\src\sitkImageReaderBase.cxx:82:
sitk::ERROR: Unable to determine ImageIO reader for "E:\BraTS19_2013_10_1_seg.nii"
Also when trying to do it a little differently:
input = gzip.GzipFile(segmentation_zipped, 'rb')
s = input.read()
input.close()
segmentation_unzipped = os.path.join(segmentation_zipped.replace(".gz", ""))
output = open(segmentation_unzipped, 'wb')
output.write(s)
output.close()
I get:
RuntimeError: Exception thrown in SimpleITK ReadImage: C:\d\VS14-Win64-pkg\SimpleITK-build\ITK\Modules\IO\PNG\src\itkPNGImageIO.cxx:101:
itk::ERROR: PNGImageIO(0000022E3AF2C0C0): PNGImageIO failed to read header for file:
Reason: fread read only 0 instead of 8
can anyone help?
No need to unzip the Nifti images, libraries such as Nibabel can handle it without decompression.
#==================================
import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
#==================================
# load image (4D) [X,Y,Z_slice,time]
nii_img = nib.load('path_to_file.nii.gz')
nii_data = nii_img.get_fdata()
fig, ax = plt.subplots(number_of_frames, number_of_slices,constrained_layout=True)
fig.canvas.set_window_title('4D Nifti Image')
fig.suptitle('4D_Nifti 10 slices 30 time Frames', fontsize=16)
#-------------------------------------------------------------------------------
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
for slice in range(number_of_slices):
# if your data in 4D, otherwise remove this loop
for frame in range(number_of_frames):
ax[frame, slice].imshow(nii_data[:,:,slice,frame],cmap='gray', interpolation=None)
ax[frame, slice].set_title("layer {} / frame {}".format(slice, frame))
ax[frame, slice].axis('off')
plt.show()
Or you can Use SimpleITK as following:
import SimpleITK as sitk
import numpy as np
# A path to a T1-weighted brain .nii image:
t1_fn = 'path_to_file.nii'
# Read the .nii image containing the volume with SimpleITK:
sitk_t1 = sitk.ReadImage(t1_fn)
# and access the numpy array:
t1 = sitk.GetArrayFromImage(sitk_t1)

Argument error when compiling .exe from Python using PyInstaller

I am trying to write a screen recorder program in python. My code runs normally in the compiler. But when I convert it to .exe, it raises this error:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): project.avi in function 'cv::icvExtractPattern'
I used pyinstaller to convert to .exe.
This is my code:
from tkinter import*
from tkinter import messagebox as msj
from PIL import ImageTk, Image
from PIL import ImageGrab
import os
import time
import cv2
import numpy as np
import glob
recording=False
i = 0
size = 100, 100
mainWindow=Tk()
mainWindow.title("ScreenRecorder")
mainWindow.geometry("200x200")
scriptDirectory = (os.path.dirname(os.path.realpath(__file__)))
def convert(imageCount):
img_array = []
for ip in range(1,imageCount):
x="snap"+str(ip)+".jpg"
for filename in glob.glob(x):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 9, size)
for iz in range(len(img_array)):
out.write(img_array[iz])
out.release()
for a in range(1,imageCount+1):
os.remove("snap"+str(a)+".jpg")
def record():
global i
print(recording)
if(recording==True):
i+=1
fileName= ("snap"+str(i))
#time.sleep(0.00005)
image = ImageGrab.grab()
name=fileName+".jpg"
image.save(name,'JPEG')
imgX = (Image.open("snap"+str(i)+".jpg"))
imgX= imgX.resize(size, Image.ANTIALIAS)
imgX=ImageTk.PhotoImage(imgX)
mainWindow.after(1, record)
def startButton():
global recording
print("ehe")
recording=True
record()
def stopButton():
global recording
recording=False
record()
convert(i)
startButton=Button(text="Start",command=startButton)
startButton.pack()
stopButton=Button(text="Stop",command=stopButton)
stopButton.pack()
mainWindow.after(1, record)
mainWindow.mainloop()
I can just advise you to use another method, i think it's more simple, try to use 'auto py to exe'.This is a module that can be installed from the net or from the pip installer.
see from here.This the only way that i use for my codes.
Secondly, iknow that if the program is not opened using the format of .py will never be opened at .exe
hope i helped you.

python cv2.imread return none on 6th image

I am trying to import and read all images in a folder. However, when I have more than 5 images, cv2.imread returns none for the 6th image. I have tried using different file names, different files, etc, but I can't get it to work.
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tkinter import filedialog
import os
from mpl_toolkits.mplot3d import Axes3D
global scan_dir
scan_dir = filedialog.askdirectory()
print(scan_dir)
x=os.listdir(scan_dir)
img={}
print(x)
for i in range(0,len(x)):
print(i)
img[i] = cv2.imread(x[i], cv2.IMREAD_GRAYSCALE)
indices[i] = np.where(img[i]<100)
I get the following error...(None is the return of print(img[i] on 6th iteration of the loop)
None
Traceback (most recent call last):
File "C:\CodeRepository\US-3D\GettingCloser.py", line 55, in <module>
indices[i] = np.where(img[i]<100)
TypeError: '<' not supported between instances of 'NoneType' and 'int'
I have the same problem if I try this
global scan_dir
scan_dir = filedialog.askdirectory()
print(scan_dir)
x=os.listdir(scan_dir)
img = cv2.imread(x[5], cv2.IMREAD_GRAYSCALE)
It will return that img is None. This is true for anything beyond the 5th image.
Must be something wrong with the file. dicts are an unordered Data structure. Should not give error always on 5th iteration. However, I have made the changes which will not throw the error. But you need to debug that image
for i in range(0,len(x)):
print(i)
img[i] = cv2.imread(x[i], cv2.IMREAD_GRAYSCALE)
if img[i]:
indices[i] = np.where(img[i]<100)

Resources