I keep getting the error: "Unknown C++ exception from OpenCV code" - python

I'm trying to run motion saliency on a video and see the results. However, I keep getting this particular error:(ret, img_sal) = saliency.computeSaliency(gray)
cv2.error: Unknown C++ exception from OpenCV code
Here is the code below:
import cv2
vid = cv2.VideoCapture('vids/test.mp4')
saliency = cv2.saliency.MotionSaliencyBinWangApr2014_create()
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
fps = vid.get(cv2.CAP_PROP_FPS)
print(fps)
while True:
success, frame = vid.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
(ret, img_sal) = saliency.computeSaliency(gray)
saliencyMap = (img_sal * 255).astype('uint8')
cv2.imshow('Map', saliencyMap)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cv2.destroyAllWindows()
vid.release()
I would also appreciate if any other errors could be pointed out. I'm trying to save the video after applying motion saliency, so any help to that would be highly appreciated. Thank you.

Related

Occurred error : CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638

I'm a beginner for python.
as below code. I need to record vedio,but after run code. it not show the image.
please help me
python 3.9
opencv 4.6
import cv2
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
result = cv2.VideoWriter('Output.avi', fourcc, 60.0,(640,480))
while (cap.isOpened()): # check Video
check , frame = cap.read()
if check == True :
cv2.imshow("Output", frame)
result.write(frame)
if cv2.waitKey(1) & 0xFF == ord("e"):
break
result.release()
cap.release()
cv2.destroyAllWindows()
I try to check camera device. so i open them by application. it can work normally

Mediapipe process() first 'self' argument

I am trying to use mediapipe to track hands. I am using Python 3.7.9 on Windows 10, my code is below:
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
cap = cv2.VideoCapture(0)
while (True):
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = mp_hands.Hands.process(imgRGB)
print(result)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
I'm getting this error:
Traceback (most recent call last):
File "C:/Users/Tomáš/PycharmProjects/pythonProject/hand_detect.py", line 11, in <module>
results = mp_hands.Hands.process(imgRGB)
TypeError: process() missing 1 required positional argument: 'image'
[ WARN:1] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Error says that I need to pass one more argument 'self' before I pass argument 'image'. I've been browsing a lot and every related code doesnt use first argument in the process() function. Could anyone help me solve this error?
The problem is that you do not create an object of mp_hands.Hands before you want to process it. The following code solves it and prints some results. By the way, this was well documentated in the documentation link i commented before.. :
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # i had problems before reading webcam feeds, so i added cv2.CAP_DSHOW here
while True:
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# you have to create an object of mp_hands.Hands to get results
# alternatively you could do: results = mp_hands.Hands().process(imgRGB)
with mp_hands.Hands() as hands:
results = hands.process(imgRGB)
# continue loop if no results were found
if not results.multi_hand_landmarks:
continue
# print some results
for hand_landmarks in results.multi_hand_landmarks:
print(
f'Index finger tip coordinates: (',
f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x}, '
f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y})'
)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
Edit:
This is more or less the same code from here:
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
# initialize webcam
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
with mp_hands.Hands(model_complexity=0,
min_detection_confidence=0.5,
min_tracking_confidence=0.5) as hands:
while cap.isOpened():
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
# If loading a video, use 'break' instead of 'continue'.
continue
# To improve performance, optionally mark the image as not writeable to
# pass by reference.
image.flags.writeable = False
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = hands.process(image)
# Draw the hand annotations on the image.
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(
image,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing_styles.get_default_hand_landmarks_style(),
mp_drawing_styles.get_default_hand_connections_style())
# Flip the image horizontally for a selfie-view display.
cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()

Opencv giving a C++ exception error form my python code

While making a barcode scanner I am facing the issue with opencv. \
My code is:
import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar
video = cv2.VideoCapture(1)
while True:
cap, frame = video.read()
rot = cv2.rotate(frame, cv2.ROTATE_180)
decodedObjects = pyzbar.decode(rot)
for obj in decodedObjects:
print("Product", obj.data)
cv2.imshow("Frame", rot)
key = cv2.waitKey(1)
if key == 27:
break
cv2.destroyAllWindows
When I execute this code, it gives me an error.
cap, frame = video.read()
cv2.error: Unknown C++ exception from OpenCV code
All kinds of support will be appreciated.

How to make pyttsx3 stop talking in real-time video capturing in python

The code below shows the face and produces an output using voices. The problem is I'm unable to stop the voices, I want it to say it only once not for each frame taken
P.S I've tried using a timer but it didn't work.
import cv2
import pyttsx3
cap = cv2.VideoCapture(0)
voiceEngine = pyttsx3.init()
while(True):
# Capture frame-by-frame
success, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if success:
voiceEngine.say("hello there")
voiceEngine.runAndWait()
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == 27:
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This is what flags are for.
said = False
while True:
...
if success and not said:
voiceEngine.say("hello there")
voiceEngine.runAndWait()
said = True

OpenCV error: (-215) scn == 3 || scn == 4 in function ipp_cvtColor

I tried playing a video from a file, as given in the tutorials. My program was as follows:
import numpy as np
import cv2
cap = cv2.VideoCapture('output.avi')
while(cap.isOpened()):
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('outVideo',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
But I got the following error:
Traceback (most recent call last):
File "playVideo.py", line 8, in <module>
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/hp/opencv/modules/imgproc/src/color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function ipp_cvtColor
I checked ret and it turned out to be False.
So the actual problem is with saving video. I used the following code to save 'output.avi' using VideoWriter function:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fourCc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourCc,20.0,(640,480))
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
cap.release()
out.release()
cv2.destroyAllWindows()
I am not able to open 'output.avi', even using VLC
First :
check ret value with: ret==True
Second as tutorials said:
Make sure proper versions of ffmpeg or gstreamer is installed. Sometimes, it is a headache to work with Video Capture mostly due to wrong installation of ffmpeg/gstreamer.
from:
http://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html#gsc.tab=0
Finally check the video codec:
Can't open video with opencv2
Change the "while"- loop parameter to "ret" - and the order of the cap.read()
- ret is True if there is a valid next frame in the video/file stream.
import numpy as np
import cv2
cap = cv2.VideoCapture('output.avi')
ret, frame = cap.read()
while(ret):
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('outVideo',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
ret, frame = cap.read()
cap.release()
cv2.destroyAllWindows()
I had faced the same error. But the issue was due to a missing package. It wasn't detected while using a jupyter notebook, but it showed up when I run the .py through terminal.
sudo apt-get install python-tk
This solved the error for me, hope it helps somebody else too :)

Categories