i am just learning image processing but cvtColor function is not working properly. it is showing following error.
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp, line 3737
Traceback (most recent call last):
File "harriscorner.py", line 6, in <module>
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.error: /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
actually i am trying harris corner detection method but cvtColor fucion is not working. help from anyone will be appreciated.
here is my code.
import cv2
import numpy as np
filename = 'chessboard.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv2.imshow('dst',img)
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Since your code is showing error at the very first cvtColor after reading from a file, it is possible that the imread operation was not successful.
Start by ensuring that your image is correctly read:
filename = 'chessboard.jpg'
img = cv2.imread(filename)
cv2.imshow("src",img)
cv2.waitKey(0)#proceed to remaining code when you press a key
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
If you're not able to see you image in this imshow, then check if the filePath is correct.
Try this:
filename = './chessboard.jpg'
Related
def AHE(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
eq = clahe.apply(gray)
return eq
IMG_SIZE = (120,120)
batch_size = 8
epoch = 10
train_image_generator = ImageDataGenerator(rescale=1./119,rotation_range=30, horizontal_flip=0.5, preprocessing_function=AHE)
validation_image_generator = ImageDataGenerator(rescale=1./119)
test_image_generator = ImageDataGenerator(rescale=1./119,preprocessing_function=AHE)
train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,
directory=train_dir,
shuffle=True,
target_size=IMG_SIZE,
)
val_data_gen = validation_image_generator.flow_from_directory(batch_size=batch_size,
directory=validate_dir,
shuffle=True,
target_size=IMG_SIZE,
)
test_data_gen = test_image_generator.flow_from_directory(batch_size=batch_size,
directory=test_dir,
shuffle=True,
target_size=IMG_SIZE,
)
sample_test_images, labels = next(test_data_gen)
print(labels[0:10])
sample_test_images.shape
labels.shape
Even Though I converted the image to gray scale I'm getting this ERROR:
OpenCV(4.1.2) /io/opencv/modules/imgproc/src/clahe.cpp:351: error: (-215:Assertion failed) _src.type() == CV_8UC1 || _src.type() == CV_16UC1 in function 'apply'
I ran into just the same problem, exactly. What is asserted is significant here:
(-215:Assertion failed) _src.type() == CV_8UC1 || _src.type() == CV_16UC1
This says that the apply function is expecting to receive specific types, either "CV_8UCI" or "CV_16UCI." These correspond to np.unit8 or np.uint16, respectively, so changing the type of the input array resolves the error.
Another issue that then came up was that the shape of the image array was no longer of the same shape as the input to the preprocessing_function. According to the Keras documentation, "The function should take one argument: one image (Numpy tensor with rank 3), and should output a Numpy tensor with the same shape." To resolve this issue, I reconverted the image back to RGB color (3 channels). (BGR is native to OpenCV, but I changed to convert to and from RGB.) I also converted the array back to np.float32 type.
So your function may be along these lines:
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
def AHE(img):
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray = gray.astype(np.uint16)
eq = clahe.apply(gray)
eq = cv2.cvtColor(eq, cv2.COLOR_GRAY2RBG)
eq = eq.astype(np.float32)
return eq
BTW, with this added preprocessing, the time for each epoch has about tripled (GPU on a Colab notebook). Working with classifying chest x-rays at the moment, I hope the enhancement is worth the overhead. ;)
def camera(transform):
capture = cv2.VideoCapture(0)
while True:
ret, frame = capture.read()
cv2.imshow('video', frame)
# esc
if cv2.waitKey(1) == 27:
photo = frame
break
capture.release()
cv2.destroyAllWindows()
img = Image.fromarray(cv2.cvtColor(photo, cv2.COLOR_BGR2RGB))
img = img.resize([224, 224], Image.LANCZOS)
if transform is not None:
img = transform(img).unsqueeze(0)
return img
This is my code to get image from the camera,
image_tensor = img.to(device)
And I have an error at the line above...
Traceback (most recent call last):
File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 126, in <module>
main(args)
File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 110, in main
caption = Image_Captioning(args, img)
File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 88, in Image_Captioning
image_tensor = img.to(device)
AttributeError: 'Image' object has no attribute 'to'
The error is like this.
If I have the image as png file and reload it with PIL, it works.
But the one I want is to use the image without saving.
Pls... Someone save me...
You could convert your PIL.Image to torch.Tensor with torchvision.transforms.ToTensor:
if transform is not None:
img = transform(img).unsqueeze(0)
tensor = T.ToTensor()(img)
return tensor
having imported torchvision.transforms as T
i am getting a (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' while making a face detection using openCv. Here is my code:
import cv2
import numpy as np
# Load HAAR face classifier
face_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
# Load functions
def face_extractor(img):
# Function detects faces and returns the cropped face
# If no face detected, it returns the input image
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(gray, 1.3, 5)
if faces is ():
return None
# Crop all faces found
for (x,y,w,h) in faces:
cropped_face = img[y:y+h, x:x+w]
return cropped_face
# Initialize Webcam
cap = cv2.VideoCapture(0)
count = 0
# Collect 100 samples of your face from webcam input
while True:
ret, frame = cap.read()
if face_extractor(frame) is not None:
count += 1
face = cv2.resize(face_extractor(frame), (200, 200))
face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
# Save file in specified directory with unique name
file_name_path = './faces/user/' + str(count) + '.jpg'
cv2.imwrite(file_name_path, face)
# Put count on images and display live count
cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Face Cropper', face)
else:
print("Face not found")
pass
if cv2.waitKey(1) == 13 or count == 100: #13 is the Enter Key
break
cap.release()
cv2.destroyAllWindows()
print("Collecting Samples Complete")
and here is the output which is an error
error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
I tried converting / to \ but that resulted in another SyntaxError: EOL while scanning string literal.
Please help me solving this issue i have also tr
You need to specify the path to your haarcascade_frontalface_default.xml file.
Put double \ in your path as i did
I modified your code and hope it helps
`#importing library
import cv2
import numpy as np
# Load HAAR face classifier
face_classifier =
cv2.CascadeClassifier
('D:\\OpenCV\\opencv\\build\\etc\\Haarcascades\\haarcascade_frontalface_default.xml')
# crop the image into 20 by 20 px and change it to B&W
def face_extractor(img):
# Function detects faces and returns the cropped face
# If no face detected, it returns the input image
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(gray, 1.3, 5)
if faces is ():
return None
# Crop all faces found
for (x,y,w,h) in faces:
cropped_face = img[y:y+h, x:x+w]
return cropped_face
#Asks for the total number of users
num=int(input("Enter no of user you want to add "))
user=1
# Initialize Webcam
cap = cv2.VideoCapture(0)
#count the total number of faces
count = 0
print("Start Capturing the input Data Set ")
d=input('Enter Face name')
# Collect 100 samples of your face from webcam input
while True:
ret, frame = cap.read()
print(type(frame))
#condition to check if face is in the frame or not
if face_extractor(frame) is not None:
count += 1
face = cv2.resize(face_extractor(frame), (200, 200))
face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
# Save file in specified directory with unique name
file_name_path = './faces/user/' +str(d)+'-' +str(count) + '.jpg'
cv2.imwrite(file_name_path, face)
# Put count on images and display live count
cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Face Cropper', face)
else:
print("Face not found")
pass
#checks if ech user 100 images is captured
if(count%100)==0 and count!= num*100 and count!=0:
print("Place the new user Signature")
cv2.waitKey()
#checks if total images are captured
if cv2.waitKey(1) == 13 or count == num*100: #13 is the Enter Key
break
#closes all windows
cap.release()
cv2.destroyAllWindows()
print("Collecting Samples Complete")`
System Architecture:
Fedora 27
OpenCV 3.4
Python 3.6
The issue produced from the following code:
def capture_input():
cap = cv2.VideoCapture(0)
while 1:
# Take each frame
ret = cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 45)
ret = cap.set(cv2.CAP_PROP_FRAME_WIDTH, 45)
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
cv2.imshow("Detecting Digits Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
frame = cv2.resize(frame, (45, 45))
break
cap.release()
cv2.destroyAllWindows()
return frame
The code works as expected sometimes, the other times it refuses to run producing:
select timeout
cv2.error:/io/opencv/modules/core/include/opencv2/core/mat.inl.hpp:500: error: (-215) total() == 0 || data != __null in function Mat
Not only that. Moreover, the webcam does not even work after that, I tried opening it with Cheese, it show a black screen and buttons are grayed out.
I tried to follow these SO links:
Issue 1
Issue 2
but with no success, and same for the other GitHub links.
Thanks in advance.
I use opencv to open a video, process frame by frame and write it back to a video. For some videos, this works fine, but for others, I got this wired error when I try to write the frames back to a video:
cv2.error: /home/xxx/Documents/opencv_videos/opencv/modules/videoio/src/cap_mjpeg_encoder.cpp:829: error: (-215) img.cols == width && img.rows == height && channels == 3 in function write
Here is what my code looks like:
cap = cv2.VideoCapture('cut.avi')
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('output.avi',fourcc, 25.0, (1280,720))
count = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
processed_frame = PROCESS(frame)
cv2.imwrite('temp.jpg',processed_frame)
out.write(processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
I can, however, use cv2.imwrite to write the process frame to a jpeg image on disk. Does anyone know where this error comes from? Thanks!