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
Related
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.
I am trying to overlay multiple image maintaining pixel intensity. I am trying to overlay based on the following documentation,
https://automaticaddison.com/how-to-blend-multiple-images-using-opencv/
I tried following to overlay two frame together using following,
dst1 = cv2.addWeighted(img1, 1, img2, 1, 0)
It produces expected output with 2 frame,
But if tried to overlay with multiple frame using following program(based on above documentation)
first_img = list_[0]
for img in range(len(list_)):
if img ==0:
pass
else:
alpha = 1/(len(list_)+1)
beta = 1-alpha
dts = cv2.addWeighted(first_img,alpha,list_[img],beta,0)
But it produced following error
Overload resolution failed:src1 is not a numpy array
neither a scalarExpected Ptrcv::UMat for argument ‘src1’
Array of image is loaded from the folder using the following program,
def read_img(img_list, img):
n = cv2.imread(img, 0)
img_list.append(n)
return img_list
path = glob.glob("*.jpg")
list_ = []
cv_image = [read_img(list_, img) for img in path]
I am trying to perform image registration for two RGB lung mask images of size 128x128. This had worked fine for other images when I was learning image registration but now somehow it throws such error. I am a newbie learning this, any help is appreciated.
I have attached the code of what I am trying to do below, where I have created a registerImage function by following GeeksForGeeks and passed images which I want to register.
import cv2
import numpy as np
def registerImage(img1,img2):
# Open the image files.
img1_color = img1 # Image to be aligned.
img2_color = img2 # Reference image.
# Convert to grayscale.
img1 = cv2.cvtColor(img1_color, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)
height, width = img2.shape
# Create ORB detector with 5000 features.
## used to creates keypoints on the reference image
orb_detector = cv2.ORB_create(5000)
# Find keypoints and descriptors.
# The first arg is the image, second arg is the mask
# (which is not required in this case).
kp1, d1 = orb_detector.detectAndCompute(img1, None)
kp2, d2 = orb_detector.detectAndCompute(img2, None)
# Match features between the two images.
# We create a Brute Force matcher with
# Hamming distance as measurement mode.
#Brute-Force matcher is simple.
#It takes the descriptor of one feature in first set and is matched with all other features in second set using some distance calculation. And the closest one is returned.
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True)
# Match the two sets of descriptors.
matches = matcher.match(d1, d2)
# Sort matches on the basis of their Hamming distance.
matches.sort(key = lambda x: x.distance)
# Take the top 90 % matches forward.
matches = matches[:int(len(matches)*0.9)]
no_of_matches = len(matches)
# Define empty matrices of shape no_of_matches * 2.
p1 = np.zeros((no_of_matches, 2))
p2 = np.zeros((no_of_matches, 2))
for i in range(len(matches)):
p1[i, :] = kp1[matches[i].queryIdx].pt
p2[i, :] = kp2[matches[i].trainIdx].pt
# Find the homography matrix.
homography, mask = cv2.findHomography(p1, p2, cv2.RANSAC)
# Use this matrix to transform the
# colored image wrt the reference image.
transformed_img = cv2.warpPerspective(img1_color,
homography, (width, height))
# Save the output.
# cv2.imwrite('output.jpg', transformed_img)
img1_show = cv2.resize(img1_color,(320,320))
img2_show = cv2.resize(img2_color,(320,320))
img3_show = cv2.resize(transformed_img,(320,320))
img = np.concatenate((img1_show,img2_show,img3_show), axis=1)
cv2_imshow(img)
ref_path = path + "/mask_0.png"
test_path = path + "/mask_8.png"
from google.colab.patches import cv2_imshow
ref_mask = cv2.imread(ref_path)
cv2_imshow(ref_mask)
test_mask = cv2.imread(test_path)
cv2_imshow(test_mask)
registerImage(ref_mask,test_mask)
############################################################################
Error:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-18-b7a8933e693e> in <module>()
----> 1 registerImage(ref_mask,test_mask)
<ipython-input-2-3a703c66a8e0> in registerImage(img1, img2)
54 # colored image wrt the reference image.
55 transformed_img = cv2.warpPerspective(img1_color,
---> 56 homography, (width, height))
57
58 # Save the output.
error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/imgwarp.cpp:3167: error: (-215:Assertion failed) (M0.type() == CV_32F || M0.type() == CV_64F) && M0.rows == 3 && M0.cols == 3 in function 'warpPerspective'
Go backwards from where you got the error and trace it back to find what is giving you the error.
You're getting errors at this statement:
transformed_img = cv2.warpPerspective(img1_color,
homography, (width, height))
What I'd suggest is to check the variables themselves that are fed into the function. Here's a crude but simple way to do it.
# Place these statements prior to the error and check their values
print("hemography:",hemography) # In my case this was None, which is why I got an error
print("h:",height,"w:", width) # Check width/height seems correct
cv2_imshow(img1_color) # Check image is loaded properly
Also worth noting if it comes up while others are searching. For similar code I got an error at the matches.sort(..) line due to the type being Tuple and not a list.
To fix it I changed it to the following:
matches = sorted(matches,key=lambda x:x.distance, reverse=False)
Debugging is a skill you'll pickup over time, as are asking/answering questions here. That error isn't simple to understand if you're new to python, which is how I found this in the first place. The documentation will become easier to understand over time also.
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)
trying to apply a gabor filter to a list of images using skimage, and save the images in a directory. The filter gets applied fine, but I cant save the now transformed images. Here is my code
num = 0
imagePaths = list(paths.list_images("../Desktop/Positive"))
for (i, imagePath) in enumerate(imagePaths):
image = cv2.imread(imagePath)
image = rgb2gray(image)
image = gabor(image, frequency=0.45, theta=.90)
image = image=(np.array(image))
image = gray2rgb(image)
image = cv.fromarray(image)
cv.SaveImage('pic'+str(num)+'.jpg', image)
The error I get is as follows:
error Traceback (most recent call last)
in ()
14 cv.SaveImage('pic'+str(num)+'.jpg', image)
error: image.channels() == 1 || image.channels() == 3 || image.channels() == 4
Is this happening because its trying to save all channels in all images as one? Thanks for any answers!