How can I save each image to a folder from this array on jupyter notebook? - save

I have an array full of 25 images, with a shape of (25, 64, 128, 1). I'm trying to save each image as jpg into a folder.
Thank you!

Install PIL using pip install Pillow. Let's assume arr is the array of shape (25, 64, 128, 1).
from PIL import Image
for i in range(arr.shape[0])
im = Image.fromarray(arr[i, :, :, 0])
im.save(f"image_{i}.jpeg")

Related

Type Error for Image generation GAN model

I am trying to visualize the final images from the generator model for GAN image generator, everything else worked perfectly.
When trying to visualize the images after training the model I am getting TypeError.
This is what i was going for image plotting:
imgs = test_model.predict(tf.random.normal((16, 128, 1)))
^ this ran fine
but the one below gave me an error:
fig, ax = plt.subplots(ncols = 4, nrows = 4, figsize = (20, 20))
for r in range(4):
for c in range(4):
ax[r][c].imshow(imgs[(r+1)*(c+1)-1])
This is the error.
TypeError: Invalid shape (28, 28, 1) for image data
Anyone can tell me how to fix this ?
I checked for all possible errors, couldn't find it.
What am I missing to check?

Issue using patchify library to open image files.,

I was trying to stitch smaller patches of images into one large image using the patchify library and the code used by DigitalSreeni on Youtube in episode 208 of multiclass semantic segmentation. However when using the below piece of code, i wasn't able to open the image files from the very beginning. It asked me to take a look at the directory or the file itself, but i knew the directory was correct. Code and error has been attached below.
from patchify import patchify, unpatchify
large_image = cv2.imread("Users/anish/largeimages/largeimage.png", 0)
#This will split the image into small images of shape [3,3]
patches = patchify(large_image, (128, 128), step=1)
Error shown on command prompt:
from patchify import patchify, unpatchify
large_image = cv2.imread("Users/anish/largeimages/largeimage.png", 0)
#This will split the image into small images of shape [3,3]
patches = patchify(large_image, (128, 128), step=1)
Traceback (most recent call last):
File "C:\Users\anish\AppData\Local\Temp\ipykernel_23432\463661116.py", line 5, in <module>
patches = patchify(large_image, (128, 128), step=1)
File "C:\Users\anish\anaconda3\envs\py37gpu\lib\site-packages\patchify\__init__.py", line 32, in patchify
return view_as_windows(image, patch_size, step)
File "C:\Users\anish\anaconda3\envs\py37gpu\lib\site-packages\patchify\view_as_windows.py", line 21, in view_as_windows
raise TypeError("`arr_in` must be a numpy ndarray")
TypeError: `arr_in` must be a numpy ndarray
[ WARN:0#9.588] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('Users/anish/largeimages/largeimage.png'): can't open/read file: check file path/integrity

Denoising multiple grayscaled text images using Opencv [duplicate]

This question already has answers here:
What does OpenCV's cvWaitKey( ) function do?
(9 answers)
what does waitKey (30) mean in OpenCV? [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to denoise multiple gray-scaled text images from a folder. I have converted all the images into gray-scale already. All I want is to remove noise or blurriness from all the images without changing text. For this, I am using opencv in order to remove blurriness or noisiness. I have written the code as shown below, when I run the code it shows no error and displays nothing.Please help me to solve this problem. I am new in image processing that's why I am confused. Here's my code...
import numpy as np
from PIL import Image
import cv2
import glob
src_path = r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images\*.png" #images folder path
def get_string(src_path):
for filename in glob.glob(src_path):
img = cv2.imread(filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
cv2.imwrite(src_path + "filename", img)
You should narrow down the files you load in. This I prefer to do with glob which allows for easy regular expression patterns when searching for files. I would expect that either you get to a file that is not an image but still loaded or that you are missing a cv2.waitKey(0) to exit the view.
import cv2
from glob import glob
files = glob('*.jpg')
for filename in glob('*.jpg'):
img = cv2.imread(filename)
bilateral_blur = cv2.bilateralFilter(img, 9, 75, 75)
cv2.imshow('denoised_images', bilateral_blur)
cv2.waitKey(0)

How can I run this prediction.py and evaluate_performance.py file?

I am a medical student and I am using google colab to learn fastAI. In this project, https://github.com/QinglingGo/Classification-of-Objects-using-Deep-Learning-Model,
I can achieve the output of the model, but I don't know how to perform the prediction.py and the evaluat_performance.py files.
When I run the evaluat_performance.py, the following message will appear:
python3: can't open file 'prediction.py': [Errno 2] No such file or directory
/usr/local/lib/python3.6/dist-packages/IPython/utils/traitlets.py:5: UserWarning: IPython.utils.traitlets has moved to a top-level traitlets package.
  warn ("IPython.utils.traitlets has moved to a top-level traitlets package.")
1. Loading Data ...
ImageDataBunch;
Train: LabelList (942 items)
x: SegmentationItemList
Image (3, 256, 256), Image (3, 256, 256), Image (3, 256, 256), Image (3, 256, 256), Image (3, 256, 256)
y: SegmentationLabelList
ImageSegment (1, 256, 256), ImageSegment (1, 256, 256), ImageSegment (1, 256, 256), ImageSegment (1, 256, 256), ImageSegment (1, 256, 256)
Path: / content / drive / My Drive / Colab Notebooks / bbc_train / images;
Valid: LabelList (0 items)
x: SegmentationItemList
y: SegmentationLabelList
Path: / content / drive / My Drive / Colab Notebooks / bbc_train / images;
Test: None
2. Instantiating Model ...
Traceback (most recent call last):
  File "evaluate_preformance.py", line 66, in <module>
    combined_accuracy, classification_accuracy, bbox_score, segmentation_accuracy = evaluate ()
  File "evaluate_preformance.py", line 29, in evaluate
    M = Model (path = model_dir, file = 'export.pkl')
NameError: name 'Model' is not defined.
And I don't understand the meaning of "from sample_student import Model" in line 6 of the .py file? Can anyone help me?
Thanks in advance!
I don't know whether this will solve your problem completely or not but this is the basic things that you should keep in mind when you use such projects
Kindly go to the directory from your terminal where you can find a python script called the evaluate_performance.py code and use the command python evaluate_performance.py. I guess the deep learning model is also defined there in one of the python scripts. Set all the paths to your dataset properly and if everything is correct then you will be able to run the code successfully.
Note kindly keep all the python scripts in the same directory so that they are accessible from anywhere in the same directory. Hope this will help you.
IN a new cell of your jupyter notebook, run the below command.
%run /path_to_file/filename.py
This will execute the python file inside the jupyter notebook.
Note: Make sure you are giving the correct directory. If path is wrong then it wil raise an error that file not found

Tensorflow Image Shape Error

I have trained a classifier and I now want to pass any single image through.
I'm using the keras library with Tensorflow as the backend.
I'm getting an error I can't seem to get past
img_path = '/path/to/my/image.jpg'
import numpy as np
from keras.preprocessing import image
x = image.load_img(img_path, target_size=(250, 250))
x = image.img_to_array(x)
x = np.expand_dims(x, axis=0)
preds = model.predict(x)
Do I need to reshape my data to have None as the first dimension? I'm confused why Tensorflow would expect None as the first dimension?
Error when checking : expected convolution2d_input_1 to have shape (None, 250, 250, 3) but got array with shape (1, 3, 250, 250)
I'm wondering if there has been an issue with the architecture of my trained model?
edit: if i call model.summary() give convolution2d_input_1 as...
Edit: I did play around with the suggestion below but used numpy to transpose instead of tf - still seem to be hitting the same issue!
None matches any number. Usually, when you pass some data to a model, it is expected that you pass tensor of dimensions: None x data_size, meaning the first dimension is any dimension and denotes batch size. In your case, the problem is that you pass 250 x 250 x 3, and it is expected 3 x 250 x 250. Try:
x = image.load_img(img_path, target_size=(250, 250))
x_trans = tf.transpose(x, perm=[2, 0, 1])
x_expanded = np.expand_dims(x_trans, axis=0)
preds = model.predict(x_expanded)
Ok so using feedback rom Sygi i think i have half solved it,
The error was actually telling me i needed to pass in my dimensions as [1, 250, 250, 3] so that was an easy fix; i must say im not sure why TF is expecting the dimensions in this order as looking at the docs it doesnt seem right so more research required here.
Moving ahead im not sure transpose is the way to go as if i use a different input image the dimensions may not be in the same order meaning the transpose doesnt work properly,
Instead of transpose I'm probably trying to t call x_reshape = img.reshape((1, 250, 250, 3)) depending on what i find out about dimension order in reshaping for TS
thanks for the hints Sygi :)

Resources