The cv2.imshow not showing webcam video and not opening any window - python

I have an issue with showing up the window and cam capture using OpenCV
When i'm run the script, i see that the cam is working, but the window with this cam is not showing anywhere, i've had just the Python icon showed up but it`s even not clickable.
setup:
macOS Big Sur 11.4
python 3.8
cv2 4.2.0
I`ve tried to:
Add sleep before ret, frame = video_capture.read()
Change cv2.waitKey() to 0, 1, and 500
Had tested on my notebook cam, and on phone using IriunWebcam
Tried different IDEs(Visual code, and PyCharm), and tried to run the
script in the terminal
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
faceCascade = cv2.CascadeClassifier('/Users/***/Documents/GitHub/FaceAuth/haarcascade_frontalface_default.xml')
log.basicConfig(filename='webcam.log', level=log.INFO)
video_capture = cv2.VideoCapture(0) # 0 for phone cam, 1 for pc cam
anterior = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, 1.1, 4)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: " + str(len(faces)) + " at " + str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
This is my variables in debug breakpoint, before cv2.imshow('Video', frame)

From #idonthaveaname in the comments section:
Have you tried upgrading opencv to 4.4.0? Maybe it should work, 4.4.0 is the latest version.

Related

Why does my image taken with OpenCV appear smaller than that of libcamera?

I am currently working on a project which makes use of a Raspberry Pi and its Camera Module v2.1.
I need to scan some barcodes with the camera of which I am using the OpenCV and pyzbar libraries.
I am running into some trouble with the image that OpenCV is returning, example below:
Image returned from running libcamera-hello:
Image returned from running my script:
As you can see the images are very different, the OpenCV image is more zoomed in.
I've tried resizing the image and even changing the size of the frame but it doesn't seem to help, the image just gets stretched!
Does anyone have any ideas on why this might be happening?
My script for capturing the images is below:
import cv2
from pyzbar import pyzbar
from gpiozero import Button
from readBarcodeData import read_text
button = Button(25)
def read_barcodes(frame):
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
x, y , w, h = barcode.rect
barcode_info = barcode.data.decode('utf-8')
cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
with open("barcode_result.txt", mode ='w') as file:
file.write(str(barcode_info).replace("'", ""))
return frame
def main():
while True:
if button.is_pressed:
camera = cv2.VideoCapture(0)
ret, frame = camera.read()
while ret:
ret, frame = camera.read()
frame = read_barcodes(frame)
cv2.imshow('Barcode Scanner', frame)
if cv2.waitKey(0) & 0xFF == 27:
break
break
camera.release()
cv2.destroyAllWindows()
read_text()
if __name__ == '__main__':
main()
EDIT:
I have also tried capturing an image using the following code:
import cv2
vid = cv2.VideoCapture(0)
while(True):
# Capture the video frame
ret, frame = vid.read()
# Display the resulting frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
But I still get a cropped image.
EDIT 2:
Returned properties from the video capture:
CV_CAP_PROP_FRAME_WIDTH: '640.0'
CV_CAP_PROP_FRAME_HEIGHT : '480.0'
[ WARN:0] global /tmp/pip-wheel-j62hpwu1/opencv-python_19cf39855c924932a2df50dd2b502cd2/opencv/modules/videoio/src/cap_v4l.cpp (1911) getProperty VIDEOIO(V4L2:/dev/video0): Unable to get camera FPS
CAP_PROP_FPS : '-1.0'
CAP_PROP_POS_MSEC : '911170.05'
CAP_PROP_FRAME_COUNT : '-1.0'
CAP_PROP_BRIGHTNESS : '-1.0'
CAP_PROP_CONTRAST : '-1.0'
CAP_PROP_SATURATION : '-1.0'
CAP_PROP_HUE : '-1.0'
CAP_PROP_GAIN : '-1.0'
CAP_PROP_CONVERT_RGB : '1.0'
I managed to "fix" this by using the PiCamera library to capture the image and then run it through cv2:
Code for reading in PiCamera image is below:
import cv2
from time import sleep
from pyzbar import pyzbar
from gpiozero import Button
from picamera.array import PiRGBArray
import picamera
from readBarcodeData import read_text
button = Button(25)
def read_barcodes(frame):
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
x, y , w, h = barcode.rect
barcode_info = barcode.data.decode('utf-8')
cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
with open("barcode_result.txt", mode ='w') as file:
file.write(str(barcode_info).replace("'", ""))
return frame
def main():
while True:
if button.is_pressed:
with picamera.PiCamera() as camera:
rawCapture = PiRGBArray(camera)
#camera.resolution = (3280, 2464)
camera.start_preview()
#sleep(1)
camera.capture(rawCapture, format="bgr")
img = rawCapture.array
#camera = cv2.VideoCapture(0)
#ret, frame = camera.read()
ret = True
while ret:
#ret, frame = img
frame = read_barcodes(img)
#cv2.imshow('Barcode Scanner', frame)
#print(frame.shape)
#if cv2.waitKey(0) & 0xFF == 27:
#break
break
cv2.destroyAllWindows()
read_text()
if __name__ == '__main__':
main()
The image captured by PiCamera seems to return the full image with no cropping so works a treat.

imshow create new windows with opencv on ubuntu

I tried to show images from camera using cv2.imshow, but instead of updating it creates new windows.
This is the code
import cv2
if __name__ == '__main__':
roi_width = 300
roi_height = 300
cam = cv2.VideoCapture(0)
while True:
ret, original = cam.read()
roi = original[0:roi_height, 0:roi_width]
cv2.rectangle(original, (0, 0), (roi_width+5, roi_height+5), 5)
cv2.imshow("original", original)
cv2.imshow("roi", roi)
k = cv2.waitKey(1)
if k == ord('q'):
break
cv2.destroyAllWindows()
This is the result I got after 10 iterations

OpenCV Human Body Detection through a webcam - No detections visible

I am trying to detect the human body through OpenCV. The code throws no error. The camera also starts but it is unable to detect anything.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while (True):
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
#cv2.VideoCapture(0).release()
I highly suspect its an indentation error. The camera does start, but your code to draw the bounding boxes of the faces are outside of the loop. Just indent that code. In addition, you'll need to free the camera resource properly or the next time you run the code, the camera will not be able to capture frames properly. I've changed the release call so that it releases the grabbed resource.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while True:
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
video_captured.release() # Changed so that you're releasing the grabbed resource

Assertion fail with Open CV

I'm new to openCV and am trying to get openCV to work my USB webcam on Win7 with Python 3.8. I've got the basic tutorial from here modified from Raspberry Pi cam by the same author here.
which is:
#!/usr/bin/python3
import time
import numpy as np
import cv2
#point to the haar cascade file in the directory
cascPath = "haarcascade.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
#start the camera
video_capture = cv2.VideoCapture(0)
#give camera time to warm up
time.sleep(0.1)
#start video frame capture loop
while True:
# take the frame, convert it to black and white, and look for facial features
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# use appropriate flag based on version of OpenCV
if int(cv2.__version__.split('.')[0]) >= 3:
cv_flag = cv2.CASCADE_SCALE_IMAGE
else:
cv_flag = cv2.cv.CV_HAAR_SCALE_IMAGE
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv_flag
)
#for each face, draw a green rectangle around it and append to the image
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
#display the resulting image
cv2.imshow('Video', frame)
#set "q" as the key to exit the program when pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# clear the stream capture
video_capture.release()
cv2.destroyAllWindows()
It should run out of the box, but I get the error below and I'm not sure why. CV_flag and gray have data and the other parameters are filled. Any ideas.
C:\Users\Ghoul>py D:\LearnPython\open_cv_face_track_test.py -3.8
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674)
SourceReaderCB::~SourceReaderCB
terminating async callback
Traceback (most recent call last):
File "D:\LearnPython\open_cv_face_track_test.py", line 31, in <module>
faces = faceCascade.detectMultiScale(
cv2.error: OpenCV(4.1.2) C:\projects\opencv-
python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Ass
ertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
The faceCascade classifier is empty, which means it was unable to retrieve the classifier from the path provided.
You can replace the line
cascPath = "haarcascade.xml"
with:
cascPath = '../../haarcascade.xml'
where you provide the full path of the xml file for cascPath.

Iam having trouble with Python command “ cascPath = sys.argv[1] ” i get error IndexError: list index out of range

I am using a Raspberry Pi 3 Model B, with Raspbian, opencv 2.x and Python 3 installed.
I want to access my USB Webcam and take a picture with it. I've found tons of code but none are of any use. I found one which is better but when I run the command
cascPath = sys.argv[1]
I get the error
Traceback (most recent call last):
File "/home/pi/test.py", line 4, in
cascPath = sys.argv[1]
IndexError: list index out of range
I simply need to access my webcam to take a picture.
I am using the following code :
import cv2
import sys
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
video_capture.release()
This code try to recognize faces on image and sys.argv[1] expects you run script with path to XML file which help recognize faces.
If you don't want to recognize faces then you need only this code to display on monitor video from camera.
import cv2
import sys
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
# Display the resulting frame
cv2.imshow('Video', frame)
# exit if you press key `q`
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
video_capture.release()
Or this to save image
import cv2
video_capture = cv2.VideoCapture(0)
# Capture frame
ret, frame = video_capture.read()
# Write frame in file
cv2.imwrite('image.jpg', frame)
# When everything is done, release the capture
video_capture.release()

Categories