Getting openCV error: Assertion Failed - python

I'm using opencv 3.1 in RaspberryPi 3. I,m trying to run the following Hough Circle detection algorithm
#! /usr/bin/python
import numpy as np
import cv2
from cv2 import cv
VInstance = cv2.VideoCapture(0)
key = True
"""
params = dict(dp,
minDist,
circles,
param1,
param2,
minRadius,
maxRadius)
"""
def draw_circles(circles, output):
if circles is not None:
for i in circles[0,:]:
#draw the outer circle
cv2.circle(output,(i[0],i[1]),i[2],(0,255,0),2)
#draw the centre of the circle
cv2.circle(output,(i[0],i[1]),2,(0,0,255),3)
print("The number of circles if %d" %(circles[0].shape[0]))
elif circles is None:
print ("The number of circles is 0")
if __name__ == '__main__':
while key:
ret,img = VInstance.read()
## Smooth image to reduce the input noise
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgSmooth = cv2.GaussianBlur(imgGray,(5,5),3)
## Compute Hough Circles
circles = cv2.HoughCircles(imgSmooth,cv2.cv.CV_HOUGH_GRADIENT,1,100,
param1=80,
param2=50,
minRadius=50,
maxRadius=100)
draw_circles(circles,img)
## Display the circles
cv2.imshow('detected circles',imgGray)
cv2.imshow("result",img)
k = cv2.waitKey(1)
if k == 27:
cv2.destroyAllWindows()
break
But I'm getting Assertion Failed error, details are below.
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor,
file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
Traceback (most recent call last): File "HoughCircles.py", line 70,
in
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error:
(-215) scn == 3 || scn == 4 in function cvtColor
Can anyone please check and help!

Error code "Assertion failed (scn == 3 || scn == 4) in cvtColor" means that the input (source) image in your cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) method does not have 3 or 4 channels, which are necessary for this type of conversion. Probably your input image is already grayscale format. Try just not to use that method and your problem should be solved. If it does throw other unsolvable errors or does not solve the problem, post your issues in comments.

This means the input image is invalid, which is why you need to check the ret value in your loop!
The error and question title doesn't have anything to do with your Hough circles, so I'll condense my answer to address the assertion failure (add back in your stuff later!):
#!/usr/bin/python
import numpy as np
import cv2
VInstance = cv2.VideoCapture(0)
if __name__ == '__main__':
while True:
ret,img = VInstance.read()
# Confirm we have a valid image returned
if not ret:
break
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("result",img)
k = cv2.waitKey(1)
if k == 27:
break
cv2.destroyAllWindows()

Related

src.empty() in function 'cv::cvtColor' & Cap.read()' is not reading the video frame

Python 3.8, Opencv 4.4.0
I have loaded correctly video file it's running, I think Cap.read() is not reading the video frame. I'm working on mask detection project and want to test in pre-recorded wearing mask Video.
Full Code
# import packages
import cv2
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import numpy as np
model = load_model('model_02.h5')
img_width, img_hight = 200, 200
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture('wearingmask.mp4') # for video
img_count_full = 0
#parameters for text
font = cv2.FONT_HERSHEY_SIMPLEX
org = (1, 1)
class_lable=' '
fontScale = 1
# Blue color in BGR
color = (255, 0, 0)
thickness = 2 #1
while True:
img_count_full += 1
response, color_img = cap.read()
if response == False:
break
gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, 1.1, 6)
FULL ERROR
error Traceback (most recent call last)
<ipython-input-8-d7656fcb48d9> in <module>
39 break
40
---> 41 gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
42 faces = face_cascade.detectMultiScale(gray_img, 1.1, 6)
error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-9d_dfo3_\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
It's pretty self explanatory. Your code's core logic is basically loop through images in the video until there are no more images, and then apply cvtColor on the last image.
Your while loop breaks when response is False, that is, you've reached the end of your video file. However, when response is False, the corresponding color_img is actually None. To actually get the last valid image, you need to do something like:
while True:
img_count_full += 1
response, frame = cap.read()
if response == False:
break
color_img = frame
gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)

error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:11111: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

i have followed a tutorial on creating a training set to recognize a face
here is the 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 = r'C:\Users\madhumani\path\\' + 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 whenever i tried to run this code in my jupyter notebook i have got this error
error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:11111: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
and tried to figure out the issue by searching this over stackoverflow and all other sites even after searching i couldnt understand the reason behind this issue
here is the commplete traceback of the error
error
Traceback (most recent call last)
<ipython-input-13-6aa561124bc3> in <module>()
30
31 ret, frame = cap.read()
---> 32 if face_extractor(frame) is not None:
33 count += 1
34 face = cv2.resize(face_extractor(frame), (200, 200))
<ipython-input-13-6aa561124bc3> in face_extractor(img)
11
12 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
---> 13 faces = face_classifier.detectMultiScale(gray, 1.3, 5)
14
15 if faces is ():
and i have tried adding 2.4.13 v dll files in the python root directory as well as added them to the environment variable but still its of no use

Throwing Error at disparity in StereoBM method

I am using a fisheye camera for depth image. I had tried with StereoSGBM() method for the depth map which has not given the desired results but now I am trying it with StereoBM() method.
stereoMatcher = cv2.StereoBM() preset = 2 ndisparities = 32 WinSize = 5
if not left.grab() or not right.grab():
print("No more frames")
break
_, leftFrame = left.retrieve()
#leftFrame = cropHorizontal(leftFrame)
leftHeight, leftWidth = leftFrame.shape[:2]
_, rightFrame = right.retrieve()
#rightFrame = cropHorizontal(rightFrame)
rightHeight, rightWidth = rightFrame.shape[:2]
if (leftWidth, leftHeight) != imageSize:
print("Left camera has different size than the calibration data")
break
if (rightWidth, rightHeight) != imageSize:
print("Right camera has different size than the calibration data")
break
fixedLeft = cv2.remap(leftFrame, leftMapX, leftMapY, REMAP_INTERPOLATION)
fixedRight = cv2.remap(rightFrame, rightMapX, rightMapY, REMAP_INTERPOLATION)
grayLeft = cv2.cvtColor(fixedLeft, cv2.COLOR_BGR2GRAY)
grayRight = cv2.cvtColor(fixedRight, cv2.COLOR_BGR2GRAY)
As compute a function of StereoBM() also needs a third argument as disparity. I calculated it by using
grayLeft = cv2.cvtColor(fixedLeft, cv2.COLOR_BGR2GRAY)
grayRight = cv2.cvtColor(fixedRight, cv2.COLOR_BGR2GRAY)
disparity = stereoMatcher.compute(grayLeft, grayRight)
depth = stereoMatcher.compute(grayLeft, grayRight)
#cv2.imshow('left', fixedLeft)
#cv2.imshow('right', fixedRight)
cv2.imshow('depth', depth / DEPTH_VISUALIZATION_SCALE)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
left.release() right.release() cv2.destroyAllWindows()
But it is throwing an error which is:
Traceback (most recent call last):
File "fisheye_depth.py", line 104, in <module>
disparity = stereoMatcher.compute(grayLeft, grayRight)
TypeError: Incorrect type of self (must be 'StereoMatcher' or its derivative)
If anyone has any idea about it that what mistake I am doing. Let me know what mistake I am doing taking out the disparity for compute operator().

Issue with OpenCV in Python

I am trying to run the following code on my Raspberry Pi, but it is giving me this error:
Traceback (most recent call last):
File "video_capture_thresh.py", line 59, in
main ()
File "video_capture_thresh.py", line 11, in main
crop = frame[180:320, 0:638]
TypeError: 'NoneType' object has no attribute 'getitem
import numpy as np
import cv2
#cap=cv2.VideoCapture(0)
cap = cv2.VideoCapture(1)
def main():
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
crop = frame[180:320, 0:638]
crop2=cv2.cvtColor(crop,cv2.COLOR_BGR2GRAY)
th,crop2 = cv2.threshold(crop2,0,255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
previous = cv2.GaussianBlur(crop2, (5,5),0)
contours, hierarchy = cv2.findContours(crop2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.rectangle(previous,(0,0),(638,140),(0,255,0),5)
i=0
for cnt in contours:
moments = cv2.moments(cnt) # Calculate moments
if moments['m00']!=0:
cx = int(moments['m10']/moments['m00']) # cx = M10/M00
cy = int(moments['m01']/moments['m00']) # cy = M01/M00
moment_area = moments['m00'] # Contour area from moment
contour_area = cv2.contourArea(cnt) # Contour area using in_built function
perimeter = cv2.arcLength(cnt,True)
cv2.drawContours(previous, [cnt], 0, (0,255,0), 3)
px = previous[cy,cx]
if px == 255 :
i=i+1
cv2.circle(previous,(cx,cy),5,(0,0,255),-1)
cv2.imshow("Previous",previous)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
main ()
cap.release()
cv2.destroyAllWindows()
Try adding a check to make sure you actually read in OK before you do your processing
ret, frame = cap.read()
if ret==True:
crop = frame[180:320, 0:638]
The method read
This is the most convenient method for reading video files or capturing data from decode and return the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
Check if the image is captured from camera well.
What kind of camera are you using?
Note that cv2.VideoCapture does not work with Raspi module camera, it just works with usb webcam.

Can only run OpenCV in the ROS package source folder, but not directly in the ROS package

I am pretty new to OpenCV and Python. I am trying to use OpenCV to do some image processing of the ARDrone. However, I can only rosrun my python file in the source folder as
root#ubuntu:~/ros_workspace/sandbox/ardrone/src# rosrun ardrone ardrone_colortrack.py
In this way, there was no error and the program could be executed.
However, if I do a rosrun directly in the package folder as
root#ubuntu:~/ros_workspace/sandbox/ardrone_dii# rosrun ardrone_dii ardrone_colortrack.py
There were errors:
OpenCV Error: Assertion failed ((scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F)) in cvtColor, file /tmp/buildd/ros-hydro-opencv2-2.4.6-3precise-20131020-2223/modules/imgproc/src/color.cpp, line 3541
Traceback (most recent call last):
File "/root/ros_workspace/sandbox/ardrone/src/ardrone_colortrack.py", line 86, in <module>
main()
File "/root/ros_workspace/sandbox/ardrone/src/ardrone_colortrack.py", line 75, in main
ct.run()
File "/root/ros_workspace/sandbox/ardrone/src/ardrone_colortrack.py", line 31, in run
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.error: /tmp/buildd/ros-hydro-opencv2-2.4.6-3precise-20131020-2223/modules/imgproc/src/color.cpp:3541: error: (-215) (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) in function cvtColor
I didn't understand why this happened. The OpenCV libraries and the CV_bridge have been included in the CMakeLists.txt and the Manifest.xml.
Could anyone help me on this? Thanks.
Here is the source code:
#!/usr/bin/env python
import roslib
roslib.load_manifest('ardrone_dii')
import sys
import rospy
import cv2
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class ArdroneColorTrack(object):
def __init__(self):
self.video_src = None
self.img = None
self.bridge = CvBridge()
self.lowerb = np.array([120, 80, 80], np.uint8)
self.upperb = np.array([140, 255, 255], np.uint8)
self.subVideo = rospy.Subscriber('/ardrone/image_raw', Image, self.image_converter)
def image_converter(self, video_src):
self.video_src = video_src
try:
self.img = self.bridge.imgmsg_to_cv(self.video_src, "bgr8")
except CvBridgeError e:
print e
def display(self):
print "Getting image from the camera ..."
if not self.img:
print "Having trouble reading the raw image!!!"
return -1
print '------------------------------------------------------------'
hsv_img = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
grayimg = cv2.GaussianBlur(hsv_img, (11, 11), 0, 0)
gray_img = cv2.inRange(grayimg, self.lowerb, self.upperb)
moments = cv2.moments(gray_img, 0)
area = moments['m00']
# there can be noise in the video so ignore objects with small areas
if (area > 1000):
# determine the x and y coordinates of the center of the object
# we are tracking by dividing the 1, 0 and 0, 1 moments by the area
x = moments['m10']
y = moments['m01']
cv2.circle(gray_img, (int(x), int(y)), 2, (255, 255, 255), 20)
#display the image
cv2.imshow('Raw Image Window', self.img)
cv2.imshow('Color-tracked Window', gray_img)
cv2.waitKey(1)
def main():
rospy.init_node( 'ardrone_colortrack' )
ct = ArdroneColorTrack()
loop = rospy.Rate(1)
while not rospy.is_shutdown():
try:
ct.display()
loop.sleep()
except KeyboardInterrupt:
print "Keyboard interrupted!"
rospy.signal_shutdown('Closing ROS node!')
sys.exit()
if __name__=="__main__":
main()
The error message seems pretty clear. The instruction:
hsv_img = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
failed because one of these things happened:
scn (the number of channels of the source), i.e. self.img.channels(), is neither 3 nor 4.
depth (of the source), i.e. self.img.depth(), is neither CV_8U nor CV_32F.
So before calling cvtColor() print these information to the console and try to understand why their values doesn't match with what is expected by cvtColor().

Categories

Resources