Read files from a list of paths - python

I have downloaded a dataset for a deep learning project that contains images (.png) and the corresponding label for each image (.txt). I have all the images' paths in a list x. I want to iterate through these paths, preprocess the images using cv2, and append the new images to a new list images_data. However, every time I try to loop through it, I keep getting this same error: cv2.error: OpenCV(4.1.1) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
Even when I comment out that line of code that throws the error, I get another error when trying to resize the image.
This is the for loop I'm using to iterate through the list:
images_data = []
for file in x:
img = cv2.imread(file)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (80, 80))
images_data.append(img)
My x list looks pretty much like this:
x = [car1.png, car2.png, car3.png, car4.png, car5.png]
How can I solve this error?

That error indicates your img variable is empty so cv2.imread(file) did not read an image. You can check this after reading the image and before converting the color or resizing, with a simple if case:
if img is None:
print('Error reading image')
else:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
or check if the file exists using the os module:
img = cv2.imread(file)
if os.path.isfile(file):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
os.path.isfile(file) will return True if the file exists.
I am assuming your files, car1.png, car2.png etc are in a different folder and not in the same path with this script in which case, you need to append the directory of the images to the file name before you can read it. So for example, if your images are in, let's say, '/home/Deep_Learning/Car_Images/' then when reading the images, the variable file must contain the string: /home/Deep_Learning/Car_Images/car1.png, for the first image and not just car1.png. You can do this using python's os module like this:
import cv2
import os
# Directory of the images. Change it according your path
data_dir = '/home/Deep_Learning/Car_Images/'
images_data = []
for file in x:
file_name = os.path.join(data_dir, file) # Append the image folder with the image name
if os.path.isfile(file_name) is False: #Check if image file exists
print("Image file ", file_name, "does not exist")
else:
img = cv2.imread(file_name)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (80, 80))
images_data.append(img)

Related

why I got parameter must be 2D array error when I used imread with grayscale image?

I got an error in feature.local_binary_pattern
I used imread(img_path, cv2.COLOR_BGR2GRAY) but it didn't fix it.
The images that I read is grayScale
THE FULL Error message:
Traceback (most recent call last):
File "/Users/myname/PycharmProjects/pythonProject1/main.py", line 76, in <module>
lbp.append(feature.local_binary_pattern(img, 8, 3, method="default"))
File "/Users/myname/PycharmProjects/pythonProject1/venv/lib/python3.8/site-packages/skimage/feature/texture.py", line 333, in local_binary_pattern
check_nD(image, 2)
File "/Users/myname/PycharmProjects/pythonProject1/venv/lib/python3.8/site-packages/skimage/_shared/utils.py", line 655, in check_nD
raise ValueError(
ValueError: The parameter `image` must be a 2-dimensional array
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
import random
from skimage import feature #-> python -m pip install -U scikit-image
from PIL import ImageOps
#load and labeling the data
#__________________________________________________________________________
DIRECTORY ="/Users/myname/Desktop/LSB"
FILES = ['cover', 'stego']
data = []
for file in FILES:
path = os.path.join(DIRECTORY, file)
for img in os.listdir(path):
img_path = os.path.join(path, img)
#print(img_path)
label = FILES.index(file)
img = cv2.imread(img_path, cv2.COLOR_BGR2GRAY)
data.append([img, label])
random.shuffle(data)
X=[]
y=[]
for features, label in data:
X.append(features)
y.append(label)
X = np.array(X)
y = np.array(y)
#print(" x[3].shape->" , np.shape(X[3])) ->-> gives me : x[3].shape-> ()
#LBP feature extraction
#__________________________________________________________________________
lbp =[]
for img in X :
print( "**** image shape -> ", np.shape(img) #print only first two images
lbp.append(feature.local_binary_pattern(img, 8, 3, method="default"))
Problem is fixed
the problem was because None values in the array for some reason it read from empty file so i used if which will not read the empty file
for img in os.listdir(path):
if img!='.DS_Store':
img_path = os.path.join(path, img)
print("img path ", " ", img)
label = FILES.index(file)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
data.append([img, label])
enter image description here
enter image description here
When I run your code with image RGB then I get (512,512,3) - even if it use cv2.COLOR_BGR2GRAY in imread() - and this can make your problem.
You use wrong value in imread()- it has to be cv2.IMREAD_GRAYSCALE
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
And value cv2.COLOR_BGR2GRAY is for function
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
EDIT:
It seems you have another problem.
When cv2 can't read file then it doesn't raise error but it returns None - and later it makes problem. You will have to use if/else to skip this image
if img is not None: # can't be `if not img:`
data.append([img, label])
else:
print("can't read:", img_path)
You may have to also use some external program to convert this image to other format.

imread return None even though the image exists in the given path

images = glob.glob('../catkin_ws/src/project1/images/*.jpg')
print(images)
When I print the variable images I get all the image file like this in an array.
['../catkin_ws/src/project1/images/img1.jpg', '../catkin_ws/src/project1/images/img2.jpg', '../catkin_ws/src/project1/images/img3.jpg']
But when I try to load the images using cv2.imread it returns None.
for fname in images:
img = cv2.imread(fname)
print(img) #gets None

open cv can not read all files form a path

I am working with a dataset of 72 images and 72 masks. I appended the images into a numpy ndarrayI want the cv2 to read the files from the path corresponding to the files in the numpy ndarray.
this is the path to images and masks:
images_dir = '/content/drive/MyDrive/dataset/images'
masks_dir = '/content/drive/MyDrive/dataset/masks'
#adding the images to the numpy ndarray
file_names = np.sort(os.listdir(images_dir))
file_names = np.char.split(file_names, '.')
filenames = np.array([])
for i in range(len(file_names)):
filenames = np.append(filenames, file_names[i][0])
this is the function I want open cv to read every image and then masks from the corresponding path:
def augment_dataset(count):
'''Function for data augmentation
Input:
count - total no. of images after augmentation = initial no. of images * count
Output:
writes augmented images (input images & segmentation masks) to the working directory
'''
transform_1 = augment(512, 512)
transform_2 = augment(480, 480)
transform_3 = augment(512, 512)
transform_4 = augment(800, 800)
transform_5 = augment(1024, 1024)
transform_6 = augment(800, 800)
transform_7 = augment(1600, 1600)
transform_8 = augment(1920, 1280)
i = 0
for i in range(count):
for file in filenames:
tile = file.split('_')[1]
img = cv2.imread(images_dir+file+'.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
mask = cv2.imread(masks_dir+file+'.png')
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
when I run the code:
augment_dataset(8)
there is this error showing up:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-112-fae4beb79e15> in <module>()
----> 1 augment_dataset(8)
<ipython-input-111-121d55acd3fc> in augment_dataset(count)
20 tile = file.split('_')[1]
21 img = cv2.imread(images_dir+file+'.jpg')
---> 22 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
23 mask = cv2.imread(masks_dir+file+'.png')
24 mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
I know that this is because OpenCV did not read the files. so how can I make openCV to read the files?
In These cases, it's better to print(path/to/directory) to see if the directory is correct or not. In this case, we can see that I missed a / in the path to the directory. So Python was not able to parse the data.
also, you can use ose.path.exists(path/to/directory) to see if the path exists or not. if the returned value is False, you must check the specified path for errors

Binarize a set of images in Python

I would like to binarize a set of images that are situated in a particular directory on my computer.
I have succeeded to do it for a single image but I would like to run it automatically for all the images that are in the folder.
Here is the code that I have tried to implement :
path = r'C:\Users\Antonin\Desktop\WISSEM\IMAGES_20210303\Samplings'
arr = os.listdir(path)
for i in range(len(arr)):
file = arr[i]
### We read the grayscale image avec cv2
im_gray = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
### We binarize the image
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
### We save the binarized image
cv2.imwrite('binary_image_2.tiff', im_bw)
How can I modify the code in order to binarize each image situated in my folder, because for the moment I am not sure about the procedure in order to do so :
Binarize each image in the folder.
Save each binarized image as a new image in the same folder
Could you help me please with this issue,
Thank you a lot,
Use the result of the os.listdir().
Python allows iterating over lists/arrays with its for loop directly.
path = r'C:\Users\Antonin\Desktop\WISSEM\IMAGES_20210303\Samplings'
arr = os.listdir(path)
# iterate over every element in the directory
# file contains the filename
for file in arr:
filename = file.split('.')[0]
# do to binary …
# save as tiff with the same name but different extension
cv2.imwrite(f'{filename}.tiff', im_bw)

Trying to use multiple images in opencv imread function but not getting

import pprint as pp
original_img = cv2.imread("/content/drive/My Drive/images/image1.jpg") #here i want to use multiple images atleast 250 images.
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
I guess all your images are in the folder images. So you can use os to gett all their filenames.
import os
pth = "/content/drive/My Drive/images" # make sure it is correct
images = os.listdir(pth)
for image in images:
image_path = os.path.join(pth, image)
original_img = cv2.imread(image_path)
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
anyone can use for loop add empty folder to direct all the json files directly to the same folder using basic addition '+' operator.
for i in range():
original_img = cv2.imread("/folder path(500+ images)/" + any_empty_folder[i])

Categories

Resources