learning python with opencv - python

When I am running face detection code, I am facing following error:
Traceback (most recent call last):
File "E:\python program\s1.py", line 11, in <module> ret, frame=cap.read()
AttributeError: 'numpy.ndarray' object has no attribute 'read'
Most probably when I am running code which have ret, frame=cap.read() this type of code I get error.
Please provide solution.
My full code is this code I have taken from website only:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('..\haarcascade_frontalface_default.xml')
cap=cv2.VideoCapture(0)
scaling_factor=0.5
while True:
ret, frame=cap.read()
frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor,
interpolation=cv2.INTER_AREA)
gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_rects=face_cascade.detectMultiScale(gray, 1.3,5)
for(x,y,w,h) in face_rects:
cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0),3)
cv2.imshow('Face Detector', frame)
c=cv2.waitKey(1)
if c==27:
break
cap.release()
cv2.destroyAllWindows()

Have you verified your webcam works? The error tells cv2.VideoCapture(0) object hasn't been created as cap so that it's no cap.read() attribute. You may set webcam no. to cv2.VideoCapture(-1) for a trial if your webcam works with other application.
Apart from the error, the face_cascade data path should be specified in forward slash "/" as (../haarcascade_frontalface_default.xml) or double backslash "\\ as (..\\haarcascade_frontalface_default.xml) in Windows OS instead of backslash "\".

Related

OpenCV; Read Camera on macOS; TypeError

I try to run a camera reading code in macOS. Here is my code:
import cv2
from pyzbar.pyzbar import decode
import os
os.system("clear")
cap = cv2.VideoCapture(0)
cap.set(3 , 640)
cap.set(4 , 480)
while True:
success, img = cap.read()
for barcode in decode(img):
print(barcode.data)
print(barcode.rect)
x = barcode.data.decode('utf-8')
print(x)
cv2.imshow('Result', img)
cv2.waitKey(1)
This is current error:
Traceback (most recent call last):
File "/Users/username/Documents/Pyzbar Lesson 2.py", line 21, in <module>
for barcode in decode(img):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 207, in decode
pixels, width, height = _pixel_data(image)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 173, in _pixel_data
pixels, width, height = image
TypeError: cannot unpack non-iterable NoneType object
Please, share if I miss anything or other error in the code.
Thanks.
This code works fine on my Windows machine (after changing 'clear' to 'cls' of course).
You're getting a Type Error because decode is trying to operate on a None type. In line 21 you call for barcode in decode(img). Here it is img that is 'None` and since decode cannot handle 'None' you get the error.
I suspect that your hardware is not cooperating properly. This could be due to your camera access preferences. You can use the cap.isOpen() and cap.isValid() checks to add an additional layer of trouble shooting.
I FINALLY FOUND THE ANSWER
Apparently, for some macOS users, having 'cap.set()' in your code would give you errors. But after removing it, it works perfectly
'''
import cv2
from pyzbar.pyzbar import decode
import os
os.system("clear")
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
if not success:
break
for barcode in decode(img):
print(barcode.data)
print(barcode.rect)
x = barcode.data.decode('utf-8')
print(x)
cv2.imshow('Result', img)
cv2.waitKey(1)
'''

Why am I getting "cv2.error: Unknown C++ exception from OpenCV code" when I'm using cv2.BackgroundSubtractorKNN() in Python?

A simple program to show the feed from my webcam is running fine. I'm getting the error only when I try to run cv2.BackgroundSubtractorKNN() within the loop.
I have applied the following fix:
Uninstalled the latest version of OpenCV (which I was using) and installed an older version 4.5.4. But the error still persists.
Here's my code and the corresponding messages in the terminal.
import cv2
cap = cv2.VideoCapture(0)
mog = cv2.BackgroundSubtractorKNN()
while(True):
ret, frame = cap.read()
fgmask = mog.apply(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Message in terminal
PS D:\Python ground up\Open_CV> python -u "d:\Python ground up\Open_CV\backgroundsub.py"
Traceback (most recent call last):
File "d:\Python ground up\Open_CV\backgroundsub.py", line 7, in <module>
fgmask = mog.apply(frame)
cv2.error: Unknown C++ exception from OpenCV code
I think it's createBackgroundSubtractorKNN not BackgroundSubtractorKNN

Problem using OpenCV and Raspberry PI camera V2

I had been using the following code for the past two months with no problem whatsoever, however, just yesterday I have been getting errors using the code which I will detail as follows. The code in question is used to take photos of objects using the raspberry pi camera.
I initialize the raspberry pi camera v2 using the following code:
cap = cv2.VideoCapture('/dev/video0', cv2.CAP_V4L)
#set dimensions
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2560)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1440)
After which I take a photo from the camera and write the image to a filename using the following lines of code:
ret, frame = cap.read()
cv2.imwrite(fileName , frame)
I have been getting the following error quite recently:
[ WARN:0#26.652] global /io/opencv/modules/videoio/src/cap_v4l.cpp (1000) tryIoctl VIDEOIO(V4L2:/dev/video0): select() timeout.
Traceback (most recent call last):
File "/home/pi/Documents/proj_trash_can/main.py", line 55, in <module>
clickPicture(cam_capture, filename)
File "/home/pi/Documents/proj_trash_can/cam.py", line 22, in clickPicture
cv2.imwrite(fileName , frame)
cv2.error: OpenCV(4.5.5) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
Try this. Worked for me Using Raspberry pi 4, Bullseye. You haven't mentioned what filename is?
import cv2
import numpy as np
cap = cv2.VideoCapture('/dev/video0', cv2.CAP_V4L)
#set dimensions
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2560)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1440)
while cap.isOpened():
ret, frame = cap.read()
cv2.imwrite('Atharva_Naik.jpg' , frame)
cv2.imshow('Video', frame)
cv2.waitKey(0)
cap.release()
cv2.destroyAllWindows()

PYTHON 2.7 AttributeError: 'module' object has no attribute 'cv'

i'm using this code to record video with a PS3 camera *the code is in spanish by the way that's why i wrote "camara" and not "camera".
i'm using Python 2.7 and opencv 3.4.0.12, i'm assuming that the problem is the version of opencv but i don't think so BUT HONESTLY AT THIS POINT I DON'T KNOW WHAT'S RIGHT OR WRONG, PLEASE HELP.
When i run it i get this errors:
Traceback (most recent call last): File
"C:\Users\carls\OneDrive\Documentos\VIDEO CAMARA PS3.py", line 31, in
camara1() File "C:\Users\carls\OneDrive\Documentos\VIDEO CAMARA PS3.py", line 9, in camara1
fourcc = cv2.cv.CV_FOURCC(*"XVID") AttributeError: 'module' object has no attribute 'cv'
Also when i run the code instead of recording in the PS3 camera, the camera from my laptop turns on.
THIS IS PART OF THE CODE TOO, SORRY!
import numpy as np
import cv2
import random
import time
def camara1():
cap = cv2.VideoCapture(0)
fourcc = cv2.cv.CV_FOURCC(*"XVID")
size1 = (int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) )
out = cv2.VideoWriter('output.avi',fourcc, 20.0, size1)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
#Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
camara1() #THIS IS IN THE CODE TOO, SORRY. THIS IS THE LAST CODE LINE
Using
fourcc = cv2.VideoWriter_fourcc(*'XVID')
works for me.
Opencv version 3.x supports cv2.VideoWriter_fourcc, whereas cv2.cv.CV_FOURCC was supported by 2.4.x.

Python OpenCV Camera Error

For some reason, I cannot read camera video data using OpenCV and Python 3.
Here is the code I am using:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
cv2.imshow('frame',frame)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
This code returns the following error:
Traceback (most recent call last):
File "C:\Path\To\File\VideoTest.py", line 10, in <module>
cv2.imshow('frame',frame)
cv2.error: D:\Build\OpenCV\opencv-3.3.1\modules\highgui\src\window.cpp:339: error: (-215) size.width>0 && size.height>0 in function cv::imshow
The computer is running Windows Server 2012 R2 and has one USB webcam permanently in use in addition to the new one I am trying to read data from. I have tried changing the line cap = cv2.VideoCapture(0) to cap = cv2.VideoCapture(1) and had an identical error.
I tried replicating the error on my laptop using the same code and USB webcam, but it worked perfectly and I was able to stream the video.
**EDIT**
To debug, I ran the following program line-by-line in the Python shell.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
print(cap.read())
cap = cv2.VideoCapture(1)
print(cap.read())
The code outputted (False, None) twice.

Categories

Resources