how can i read multiple image folders? - python

i want to encoding some of folders that contain face images.
this is the code that i've been tried.
import face_recognition
import cv2
import numpy as np
import os
import glob
video_capture = cv2.VideoCapture(0)
known_face_encodings = []
known_face_names = []
# Load image folder and learn how to recognize it.
os.chdir("./coba1")
for file in glob.glob("*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
known_face_names.append("jokowi")
print(images_encoding)
#Load image folder and learn how to recognize it.
os.chdir("./coba")
for file in glob.glob("*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
known_face_names.append("amber heard")
print(images_encoding)
when i run the code, the terminal shows this warning
Traceback (most recent call last):
File "face_rec.py", line 32, in <module>
os.chdir("./coba")
FileNotFoundError: [Errno 2] No such file or directory: './coba'
is there anything wrong with my code? i really need the solution, thanks in advance !

Related

"cannot identify image file"-error when trying to load a tiff in python

I am trying to access to the temperature data stored in a tiff-file. I was provided with a python script that was supposed to be able to do this, but I keep getting the following error:
Traceback (most recent call last):
File "read_tiff.py", line 57, in <module>
im = Image.open(sourcePath)
File "/Users/myname/opt/anaconda3/lib/python3.8/site-packages/PIL/Image.py", line 2943, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file 'Testbild.tiff'
This is the relevant section of the code:
sourcePath = "Testbild.tiff"
im = []
try:
sourcePath = sys.argv[1]
except IndexError:
print('usage: python read_tiff.py filename')
sys.exit()
try:
im = Image.open(sourcePath)
except FileNotFoundError:
print('File not found: ' + sourcePath)
sys.exit()
imarray = np.array(im)
This is what I checked:
with another random tiff file it worked, so it is probably not the script but the file itself (/maybe I need to install some additional package??)
the tiff file can be opened without a problem in IrfanView and Photoscan
when prompting "file Testbild.tiff" I get "Testbild.tiff: TIFF image data, little-endian" so it definitely IS a tiff file
Is anyone able to help me out?
Cheers!
EDIT:
The import statement for Image is from PIL import Image
If necessary, these are all the import statements of the script:
import matplotlib.pyplot as plt
from PIL import Image
import sys
import numpy as np
import math
import cv2
Try using:
from skimage import io
im = io.imread(sourcePath)
This will open it directly as an array as well.
In my case, it worked to read .tif file to ndarray:
path2dir = r'C:\data\WORK\image4example'
name_img = 'Slice_25.tif'
path2img = os.path.join(path2dir, name_img)
im = cv2.imread(path2img , cv2.IMREAD_ANYDEPTH)
plt.imshow(im)

TypeError: NoneType, when trying to loop crop images

from os import listdir
import cv2
files=listdir('/home/raymond/Desktop/Test/Test') #Importing the dir for cropping
for file in files:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
crop_img = img[0:1600, 0:1600]
cv2.imwrite('/home/raymond/Desktop/Test/cropped'+file,crop_img) # write new data to img
Im trying to loop crop images, while getting an error of
Traceback (most recent call last):
File "Files.py", line 8, in <module>
crop_img = img[0:1600, 0:1600]
TypeError: 'NoneType' object is not subscriptable
(fixi) ➜ exercises
You are probably missing a slash at the end of the path here:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
Should be:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file) # reading a single image from the dir
or even better:
import os
img = cv2.imread(os.path.join('/home/raymond/Desktop/Test/Test/',file)) # reading a single image from the dir
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file)
Hello Dan Raymond,
This cannot work because Python does not add a slash (/) before listed filenames.
Which means that if you have a filename "hello", then what is appended to '/home/raymond/Desktop/Test/Test' is "hello" which results in '/home/raymond/Desktop/Test/Testhello' which does not exist.
Replace your line with this:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file)

Reading huge amount of Image data with Python and converting them into Numpy array

I just have started with Python and Numpy arrays. I am reading a huge amount of image data set located in many different folders. Although, everything is working fine when reading the images, but I continuously getting an error which I am not sure about what really is it. I tried to research for it, but unfortunately I failed to get the real answer. Please help me regarding this issue.
My code is below.
import os
import numpy as np
import matplotlib.pyplot as mpplot
import matplotlib.image as mpimg
images = []
path = "../compCarsThesisData/"
for root, _, files in os.walk(path):
current_directory_path = os.path.abspath(root)
for f in files:
name, ext = os.path.splitext(f)
if ext == ".jpg":
current_image_path = os.path.join(current_directory_path, f)
current_image = mpimg.imread(current_image_path)
images.append(current_image)
print(files)
for img in images:
print (img.shape)
The error I'm facing is below also.
File "reading.py", line 15, in <module>
current_image = mpimg.imread(current_image_path)
File "C:\Users\zeele\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\image.py", line 1359, in imread with Image.open(fname) as image:
File "C:\Users\zeele\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2618, in open
prefix = fp.read(16)
OSError: [Errno 22] Invalid argument
P.S. As a new member please don't mind if the question is unclear or not direct. Your help will be highly appreciated.
Thanks.

Python concatinating a string and an intiger counter to name content inside a folder

I am using widows 10 pro, python 3.6.2rc1. I am training a convolutional neural network made by tensorflow. As a preprocessing phase, I hae written the following code to resize each image. It works perfectly well, but since I have more than 100 training images (I made it quite low just to see how it works at the moment) with very different names, and at the end I'd like all of them follow the same naming convention as in "image001", "image002" and so on, I added a counter and use it to change the name of the image before saving it to the same folder by using cv2.imwrite(). But I am getting this error:
Traceback (most recent call last):
File "E:/Python/TrainingData/TrainingPrep.py", line 11, in <module>
cv2.imwrite(imageName,re)
cv2.error: D:\Build\OpenCV\opencv-3.2.0\modules\imgcodecs\src\loadsave.cpp:531: error: (-2) could not find a writer for the specified extension in function cv::imwrite_
import cv2
import glob
i=0
images = glob.glob("*.jpg")
for image in images:
img = cv2.imread(image,1)
counter=str(i)
re = cv2.resize(img,(128,128))
imageName = "image"+counter
cv2.imwrite(imageName,re)
i=i+1
print(counter)
I need my images have the names image001, image00x. I appreciate if you help me solve this problem.
Thank you very much.
The imwrite method expects the extension to determine the file format.
Simply change your line to (for PNG, or whatever file format you want) and it should work:
imageName = "image"+counter+".png"
You can rename the files later if you so wish, using glob.glob. A working example should be something like this:
import cv2
import glob
import os
i=0
images = glob.glob("*.jpg")
for image in images:
img = cv2.imread(image,1)
counter=str(i)
re = cv2.resize(img,(128,128))
imageName = "image"+counter+".jpg"
cv2.imwrite(imageName,re)
i=i+1
print(counter)
rename = glob.glob("images*.jpg")
for src in rename:
dst = os.path.splitext(item)[0]
os.rename(src, dst)
This method will give you the leading zeros you want in the file name:
import cv2
import glob
i=0
images = glob.glob("*.jpg")
for image in images:
img = cv2.imread(image,1)
re = cv2.resize(img,(128,128))
imageName = "image{:03d}.png".format(i) # format i as 3 characters with leading zeros
cv2.imwrite(imageName,re)
i=i+1
print(counter)

IOError: cannot identify image file when loading images from pdf files

I am trying to read scanned images from a pdf using wand and display it using PIL. But I get some error. First page of the pdf file works perfectly but the second page shows this error.
Code
from wand.image import Image
from wand.display import display
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import numpy as np
import cStringIO
tool = pyocr.get_available_tools()[0]
lang = tool.get_available_languages()[1]
req_image = []
final_text = []
image_pdf = Image(filename="DEEP_PLAST_20.700.pdf", resolution=200)
image_jpeg = image_pdf.convert('jpeg')
img_page = Image(image=image_jpeg.sequence[1])
img_buffer = np.asarray(bytearray(img_page.make_blob()), dtype=np.uint8)
print(img_buffer)
# im = PI.fromarray(img_buffer)
im = PI.open(cStringIO.StringIO(img_buffer))
I get this error.
Traceback (most recent call last):
File "ocr.py", line 43, in <module>
im = PI.open(cStringIO.StringIO(img_buffer))
File "/home/sahil/anaconda2/lib/python2.7/site-packages/PIL/Image.py", line 2452, in open
% (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringI object at 0x7fc4a8f168b0>
I don't why the code fails on the second page of the pdf whereas it works for the first one.
Any help would be appreciated!

Categories