cv2.imread file with accent (unicode) - python

I am trying to load the following file: 'data/chapter_1/capd_yard_signs\\Dueñas_2020.png'
But when I do so, cv2.imread returns an error: imread_('data/chapter_1/capd_yard_signs\Due├▒as_2020.png'): can't open/read file: check file path/integrity load file
When I specified the file name with os.path.join, I tried encoding and decoding the file
f = os.path.join("data/chapter_1/capd_yard_signs", filename.encode().decode())
But that didn't solve the problem.
What am I missing?

This is how I ended up getting it to work:
from PIL import Image
pil = Image.open(f).convert('RGB') # load the image with pillow and make sure it is in RGB
pilCv = np.array(pil) # convert the image to an array
img = pilCv[:,:,::-1].copy() # convert the array to be in BGR

Related

UnicodeDecodeError issue while looping through all the pictures in a folder using CV2

My code:
folder_angry = 'C:/Users/User/Desktop/test'
all_vald_img = []
for filename_valid in os.listdir(folder_angry):
img_valid = cv2.imread(os.path.join(folder_angry,filename_valid))
if img_valid is not None:
all_vald_img.append(img_valid)
true_image = image.load_img(img_valid)
img = image.load_img(img_valid, color_mode="grayscale", target_size=(48, 48))
Error message:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfd in position 1: invalid start byte
I encountered this error while looping through the entire folder of pictures using cv2.imread. I've tried solutions like
with open(path, 'rb') as f:
contents = f.read()
or any other solutions start with with open like many people suggested, but none of them really works. However, if I use picture one by one without loop, like
filename_valid = "path"
true_image = image.load_img(filename_valid)
img = image.load_img(filename_valid, color_mode="grayscale", target_size=(48, 48))
it works, but I have to do it one by one.
Is there any good way to tackle this down?
You are getting the error because you are passing the image itself (as NumPy array) to image.load_img, while image.load_img expects an image file name as argument.
Basically you are trying to read each image twice:
Using OpenCV:
cv2.imread returns an image (as NumPy array) in case of successful reading, and return None when reading fails.
Using Pillow:
image.load_img(file_name) loads the image using Pillow, and returns an object of type PIL.Image.Image.
The issue is that image.load_img expects a file name as an argument, and you are passing it an image (NumPy array) instead of file name.
The NumPy array is not a valid 'utf-8' string, so you are getting the error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfd in position 1: invalid start byte.
Assuming that reading each image twice is not an issue...
You may use something like the following code sample:
import os
import cv2
from keras.preprocessing import image
folder_angry = 'C:/Users/User/Desktop/test'
all_vald_img = []
all_vald_img_files = []
for filename_valid in os.listdir(folder_angry):
image_file_name = os.path.join(folder_angry,filename_valid)
img0 = cv2.imread(image_file_name) # Return the image as NumPy array in case of valid reading, and None if not valid.
if img0 is not None:
all_vald_img_files.append(image_file_name) # Append file name to the list (not the image).
true_image = image.load_img(image_file_name) # Use file name as argument to image.load_img
img = image.load_img(image_file_name, color_mode="grayscale", target_size=(48, 48))
all_vald_img.append(img)
# Showing images in all_vald_img for testing:
for img in all_vald_img:
img.show()
Note: I was guessing that you want to keep only the images loaded by image.load_img.

How to Image.open a RAW (CR2) file in python?

I have the following code for a .tif file:
img = Image.open("randompic.tif")
image = Jpeg()
image.encodeRGB("randompic.tif")
print(np.array_equal(image.total_bit_objects, np.asarray(Image.open('randompic.tif').convert('L'))))
I try to adapt it for a .CR2 file :
img = np.fromfile('IMG_4387.CR2', "uint16")
image = Jpeg()
image.encodeRGB("IMG_4387.CR2")
print(np.array_equal(image.total_bit_objects, np.asarray(Image.open('IMG_4387.CR2').convert('L'))))
However, Image.open('IMG_4387.CR2') does not work.
Do you have any idea to fix me ?
Why not try the following code. It uses simple PIL
I tried rawpy and rawkit and they had complications with Libraw.
Rawpy worked but performed a postprocessing I could not seem to understand
from PIL import Image
im = Image.open("File.CR2")
rgb_im = im.convert('RGB')
rgb_im.save('File.JPG')

Define function that takes jpeg image and save it as array

Im trying to make a function which needs as input an image file in jpg format and outputs an array every time i call it. This is what i achieved so far:
import scipy.misc as sm
import numpy as np
from PIL import Image
def imagefunc(image):
try:
i = Image.open(image)
if i.format == 'jpg':
return i.format == 'jpg'
except OSError: # Checking for different possible errors in the input file
print ('This is not a jpg image! Input has to be a jpg image!')
return False
except FileNotFoundError: # Another check for error in the input file
print ('No image was found! Input file has to be in the same directory as this code is!')
return False
imgarray = np.array(sm.imread(image, True))
return imgarray
The problem is that when i call it, "imagefunc(kvinna)" to open a jpeg picture it outputs: NameError: name 'kvinna' is not defined. What am i missing here? Is the code wrong or is it file directory problem? Thanks
Reading and Writing Images
You are not opening the image correctly, hence the Name Error
i = Image.open(image) # image should be "image_name.ext"
here image should be "kvinna.jpeg" with the extension.
so the function call will be: imagefunc("kvinna.jpeg") further check or either jpeg or jpg in your function definition.
Image.open(image) returns an Image object, later check the extension for it.

Python Image Library can't convert to pdf

I have a function to convert a bmp to pdf with PILLOW, this script I have it in non compiled version and compiled version (.exe). In the first one it works correctly, but in the second PILLOW throws an exception ('PDF'). Specifically fails in the .save ()
Paths and filename with extension are correct.
from PIL import Image
def bmp2pdf(self, file):
''' Convert a bmp file to PDF file, and delete old bmp file '''
img = Image.open(file)
output = file.replace('.bmp', '.pdf')
try:
img.save(output, "PDF", resolution=100.0)
remove(file)
except Exception as err:
print(err)
In the compiled version the output is:
'PDF'
Thx.
Follow this code.It works. 3 line code.
from PIL import Image
def bmp2pdf(self,path):
img = Image.open(path)
img.save('image.pdf','pdf')
I got a file named image.pdf with the image in it.
I had to add in my setup to generate the .exe I should import PIL and not PIL.IMAGE, so the whole module is loaded and the pdf feature is available
I'm using cx_freeze:
'Packages': [
'PyQt5.uic',
"...",
'PIL',
]

How to save image using Python

I have an image file decoded by base64.
Now, I want to save the image file to the specified directory.
the directory is described as image_dir_path
image_dir_path = '/images/store/'
image_file = base64.b64decode(image_file)
How can I save the image_file to image_dir_path?
I tried shutil.copy(image_file, image_dir_path), but it doesn't work for my case.
I'm sorry I coundn't find the question like this.
You can write any content to a file with a file object and its write method. As an example, let's grab some base64 encoded data from the web:
import base64, urllib
decoded = base64.b64decode(urllib.urlopen("http://git.io/vYT4p").read())
with open('/tmp/31558315.png', 'w') as handle:
handle.write(decoded)
You should be able to open the file under /tmp/31558315.png as a regular image.

Categories