How can I save an image with Image.thumbnail using PIL - python

Basically, I copied and paste a script, and merged it with other script, and now the script doesn't work, it says an error "NoneType object has no attribute save"Screenshot
And here's the script:
` from PIL import Image
import PIL
import os
from glob import glob
imgs = [y for x in os.walk(".") for y in glob(os.path.join(x[0], '*.png'))]
size = 32, 32
lastdir = None
for file in imgs:
img = Image.open(file)
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
file = file.replace('img', 'icon', 1)
dir = os.path.dirname(file)
try:
os.makedirs(dir)
except:
pass
if dir!=lastdir:
print(dir)
lastdir = dir
img.save(file + ".png", "PNG")`
Resize various images on various directories and save them, but the images are not saving.

The thumbnail() method modifies its object rather than returning a new one. So, this line:
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
should be:
img.thumbnail(size, resample=PIL.Image.NEAREST)

Related

How would I read a folder of images on my computer into a dataframe on Jupyter Notebooks?

This is my code right now, I have used a for loop to go through all the images in the folder and use the PIL library to read it into an array.
import cv2
import os
folder = '/Users/x/x/x/x'
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
return images
img = Image.fromarray(images_array,'RGB', dtype = object)

Python Resize all images in a folder

I have the following code that I thought would resize the images in the specified path But when I run it, nothing works and yet python doesn't throw any error so I don't know what to do. Please advise. Thanks
import cv2
import numpy as np
import os
from PIL import Image
def image_resize(folder):
images = []
num_images = 0
location = folder+"_"
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
new_img = np.array(Image.fromarray(img).resize((200, 200), Image.ANTIALIAS)) # Resize the images to 50 X 50
images.append(new_img)
num_images += 1
cv2.imwrite("{}/{}".format(location, filename), new_img)
return None
image_resize("2S1")
image_resize("SLICY")
image_resize("BRDM-2")
image_resize("BTR-60")
image_resize("D7")
image_resize("T62")
image_resize("ZIL131")
image_resize("ZSU-23_4")
all image in folder: G:\sar
help me
It does not do anything because your for loop is not finding any files in the folder. You are never passing the "G:\sar" part of the file path.

PIL Image Open is not able to open some files in a zip folder

I have about 300000 image files in a zip folder. Some of those files have path starting with '__'. PIL function Image.Open() is not able to open these files. Please suggest a way to open them. My code below:
import pandas as pd
import numpy as np
from zipfile import ZipFile
from io import BytesIO
from PIL import Image
from PIL import UnidentifiedImageError
problem_files = []
file_paths = []
img_list = []
img_size = (128,128)
with ZipFile('/XXX/YYY/ZZZ/AI_ML/Project2/words.zip') as myzip:
contents = myzip.namelist()
for i in range(0,len(contents)-1):
text = str(contents[i])
if '.png' in text:
file_paths.append(contents[i])
for path in file_paths:
img = myzip.read(path)
try:
img_data = Image.open(BytesIO(img))
except UnidentifiedImageError:
problem_files.append(path)
img_data = img_data.convert('L')
img_data = img_data.resize(img_size)
image_as_array = np.array(img_data, np.uint8)
image_as_array = np.reshape(image_as_array,(1,-1))
img_list.append(image_as_array)
This puts all the files with path starting with '__' into problem_files list
problem_files[-10:]
['__MACOSX/words/j04/j04-070/._j04-070-08-07.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-07.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-06.png',
'__MACOSX/words/j04/j04-070/._j04-070-08-06.png',
'__MACOSX/words/j04/j04-070/._j04-070-06-03.png',
'__MACOSX/words/j04/j04-070/._j04-070-06-01.png',
'__MACOSX/words/j04/j04-070/._j04-070-08-04.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-04.png',
'__MACOSX/words/j04/j04-070/._j04-070-04-05.png',
'__MACOSX/words/j04/j04-070/._j04-070-08-05.png']
There are about 100000 images in problem_files list

How to save images in a folder with for loop?

First, I have an issue with saving up every resized file with the same name to the same folder? Second, while running I can't understand if m t code works properly. Please, could you check if I am doing the resizing properly?Can't find a mistake in my code:
import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
for image in images:
with open(image,"rb") as file:
img = Image.open(file)
imgResult = img.resize((800,800), resample = Image.BILINEAR)
imgResult.save('"C:/Users/marialavrovskaa/Desktop/Images/file_%d.jpg"', 'JPEG')
print("All good")
If you want to give the images a name with a consecutive number than you've to concatenate the file name and a counter:
image_no = 1
for image in images:
# [...]
name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
imgResult.save(name, 'JPEG')
image_no += 1
Since the format of the images is PNG and they should be stored as JPEG, the format has to be convert from RGBA to RGB, by .convert('RGB'). Note, storing a RGBA image to 'JPGE' would cause an error:
import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
with open(image,"rb") as file:
img = Image.open(file)
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
imgResult.save(name, 'JPEG')
image_no += 1
print("All good")
By the way, if the file name should by kept and the image just should be stored to a file with a different extension, then then extension can be split form the file by .splitext:
import os
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = os.path.splitext(image)[0] + '.jpg'
imgResult.save(name, 'JPEG')
If you wan to store the fiel to a different path, with a different extension, then you've to extract the fiel name from the path.
See os.path. Split the path from the file name and extension by os.path.split(path), which returns a tuple of path and name.
e.g.
>>> import os
>>> os.path.split('c:/mydir/myfile.ext')
('c:/mydir', 'myfile.ext')
The split the file name and the extension by os.path.splitext(path):
>>> os.path.splitext('myfile.ext')
('myfile', '.ext')
Applied to your code this means, where file is the path, name and extension of the source image file:
import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
with open(image,"rb") as file:
img = Image.open(file)
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
image_path_and_name = os.path.split(file)
image_name_and_ext = os.path.splitext(image_path_and_name[1])
name = image_name_and_ext[0] + '.png'
file_path = os.path.join(path, name)
imgResult.save(file_path , 'JPEG')
image_no += 1
print("All good")

histogram.cpp:3915: error: (-215) _src.type() == CV_8UC1 in function cv::equalizeHist

files2 = [f for f in listdir(dstpath) if isfile(join(dstpath,f))]
for image in files2:
img = cv2.imread(os.path.join(dstpath,image))
equ = cv2.equalizeHist(img)
dstPath2 = join(dstpath,image)
cv2.imwrite(dstPath2,equ)
I have a folder consisting of grayscale images in jpg format but when I run my above code for Histogram equalization it gives me the above mentioned error. Pls help
imread load image in color mode by default. Try to use img = cv2.imread(your_image_path,cv2.IMREAD_GRAYSCALE) instead
#author: Quantum
"""
import cv2
import os
from os import listdir,makedirs
from os.path import isfile,join
path = r'' # Source Folder
dstpath = r'' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in asme folder")
# Folder won't used
files = [f for f in listdir(path) if isfile(join(path,f))]
for image in files:
try:
img = cv2.imread(os.path.join(path,image),cv2.IMREAD_GRAYSCALE)
**imgnew=cv2.equalizeHist(img)**
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,imgnew)
except:
print ("{} is not converted".format(image))
All I did was added the histeq function while my files are converted to grayscale

Categories