Python Forum
Problem with using opencv in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with using opencv in python
#1
Hello Everyone
I am using macOS Monterey and I am trying to run a simple python code to open my camera using opencv. But whenever I am running the code a pop-up is appearing where it is written that "Python quitted unexpectedly". I runned the same script using Terminal and it worked perfectly fine. I checked my camera permissions and found that there is no option of Python or opencv there in the list. Can anyone help me with it?
Reply
#2
I do not understand your post. You say you cannot run python code to open your camera, but the same script works "perfectly fine" when using Terminal? How are your running your python code when it fails, and what do you mean by "running the same script using Terminal"? Are you trying to run a shell script from Python? Can you post your program?
Reply
#3
(Feb-11-2024, 04:09 PM)deanhystad Wrote: I do not understand your post. You say you cannot run python code to open your camera, but the same script works "perfectly fine" when using Terminal? How are your running your python code when it fails, and what do you mean by "running the same script using Terminal"? Are you trying to run a shell script from Python? Can you post your program?


This is my code:

import cv2
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print("Error: Could not open camera.")
else:
    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: Could not read frame.")
            break
        cv2.imshow('Camera Feed', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()
For your question on how I Runned it using terminal -
I saved this code in my desktop. Then I opened Terminal and changed the directory (using "cd /Users/......") to the location of my file (In this case, Desktop). Then I entered ("python3 <file name>") and runned it and it worked.

I am also sharing a screenshot of the problem I am facing.    
deanhystad write Feb-12-2024, 04:10 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#4
If this is only an issue when running from IDLE, don't run from IDLE. IDLE does not run your python programs the same way as the program is run from the terminal of from other IDE's. IDLE replaces some standard Python libraries with IDLE specific libraries and it intercepts stdin, stdout and stderr. There are many correct Python programs that cannot be run in IDLE. Maybe yours is one of them.
Reply
#5
This works ok for me when I enter camON() in Idle. But make sure the camera window has focus when you press q. If you enter q in Idle, nothing happens!

def camON():
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open camera.")
    else:
        while True:
            ret, frame = cap.read()
            if not ret:
                print("Error: Could not read frame.")
                break
            cv2.imshow('Camera Feed', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    cap.release()
    cv2.destroyAllWindows()
I have to say, I don't understand this bit:

Quote:if cv2.waitKey(1) & 0xFF == ord('q')

Any help please??
Reply
#6
I can make Idle crash with this:

import cv2
path2image = '/home/pedro/Pictures/aphrodite.jpg'

# this window doesn't respond to clicking X to close
# after a while the window darkens
# click X to close and I get: "This window is not responding Force Quit?
# click Force Quit causes Idle to restart when I click the image window closed
def myApp():
    # read the image
    img = cv2.imread(path2image) # is an array
    # showing the image
    cv2.imshow('Aphrodite', img)
    # waiting using waitKey method
    key = cv2.waitKey(0)
    return key
This works fine in Idle, no restart:

# this works fine and returns 113 when I press q or 27 when I press esc
def myApp():
    # read the image
    img = cv2.imread(path2image) # is an array
    # showing the image 
    cv2.imshow('Aphrodite', img)       
    # waiting using waitKey method 
    key = cv2.waitKey(0)
    if key == 27 or key == 113:        
        cv2.destroyAllWindows()
    return key
This window will stay open for 10 seconds, or less if you press esc or q

# this window will shut after 10 seconds, or earlier if you press esc or q
def myApp():
    # read the image
    img = cv2.imread(path2image) # is an array
    # showing the image 
    cv2.imshow('Aphrodite', img)       
    # waiting using waitKey method 
    key = cv2.waitKey(10000) # wait 10 seconds
    if key == 27 or key == 113:        
        cv2.destroyAllWindows()
    else:
        cv2.destroyAllWindows()
    return key
Using camera feed, cv2.waitKey(0) is not good because it waits forever and the picture is still. Use cv2.waitKey(1) in a while loop.

I remember reading, years ago, someone used this to make his own "home security" set up.
A camera filmed his living room at night. If the image changed, he got a message!
Reply
#7
(Feb-12-2024, 04:15 PM)deanhystad Wrote: If this is only an issue when running from IDLE, don't run from IDLE. IDLE does not run your python programs the same way as the program is run from the terminal of from other IDE's. IDLE replaces some standard Python libraries with IDLE specific libraries and it intercepts stdin, stdout and stderr. There are many correct Python programs that cannot be run in IDLE. Maybe yours is one of them.

As of my understanding python is not getting access to the camera. Nor it is asking for permission. Terminal asked for access before running the code but python didn't. I talked to the apple's support and they said that this isn't an issue from their software, rather it is an issue in python.

It is not running any kind of code related to using the camera.
Reply
#8
Try this, it works for me, no problems. I can see my ugly mug!

# this works for me no problems   
def camON():
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open camera.")        
    else:
        while True:
            ret, frame = cap.read()
            if not ret:
                print("Error: Could not read frame.")
                break
            cv2.imshow('Camera Feed', frame)
            # setting waitKey(0) freezes the picture while you wait
            # cv2.waitKey(1) waits 1 millisecond so the picture stays alive
            key = cv2.waitKey(1)
            if key == 27 or key == 113: # esc or q to quit
                break                                
    cap.release()
    cv2.destroyAllWindows() 
Reply
#9
(Feb-14-2024, 12:43 PM)Pedroski55 Wrote: Try this, it works for me, no problems. I can see my ugly mug!

# this works for me no problems   
def camON():
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open camera.")        
    else:
        while True:
            ret, frame = cap.read()
            if not ret:
                print("Error: Could not read frame.")
                break
            cv2.imshow('Camera Feed', frame)
            # setting waitKey(0) freezes the picture while you wait
            # cv2.waitKey(1) waits 1 millisecond so the picture stays alive
            key = cv2.waitKey(1)
            if key == 27 or key == 113: # esc or q to quit
                break                                
    cap.release()
    cv2.destroyAllWindows() 

No, It dosen't work at all. It is not producing any output or error message
Reply
#10
Oh dear! What os are you using?

I use Ubuntu 22.04, I am doing this in Idle.

def camON():
    print('This is function camON() starting ... ')
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open camera.")     
        return   
    else:
        while True:
            ret, frame = cap.read()
            if not ret:
                print("Error: Could not read frame.")
                break
            cv2.imshow('Camera Feed', frame)
            # setting waitKey(0) freezes the picture while you wait
            # cv2.waitKey(1) waits 1 millisecond so the picture stays alive
            key = cv2.waitKey(1)
            if key == 27 or key == 113: # esc or q to quit
                break                                
    cap.release()
    cv2.destroyAllWindows()
    print(f'Escape key was {chr(key)}.')
    return key
The ouput, apart from the window with my ugly face, in Idle is:

Output:
camON() This is function camON() starting ... Escape key was q. 113
When I changed

cap = cv2.VideoCapture(0)
to
cap = cv2.VideoCapture(1)

I get this in Idle:

Output:
camON() This is function camON() starting ... Error: Could not open camera. Traceback (most recent call last): File "/usr/lib/python3.10/idlelib/run.py", line 578, in runcode exec(code, self.locals) File "<pyshell#19>", line 1, in <module> File "<pyshell#18>", line 20, in camON UnboundLocalError: local variable 'key' referenced before assignment
Could it be that you have more than 1 cam? Try a different number? Strange that you don't get any message at all.

If you run the above function camON() in Idle, do you at least see see:

Quote:This is function camON() starting ...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help for the shortest way to install a suitable version of Python, Numpy, and OpenCV. Ezzat 2 2,304 Dec-23-2021, 12:34 PM
Last Post: snippsat
  Python OpenCV window not opening in fullscreen mode Zman350x 0 3,313 Apr-29-2021, 07:54 PM
Last Post: Zman350x
  Python IDE doesn't see opencv-python package on my Jetson Nano sadhaonnisa 1 3,357 Oct-11-2020, 01:04 AM
Last Post: Larz60+
  pip3 install opencv-python fails on 'skbuild' Pedroski55 2 5,752 Sep-15-2020, 11:33 AM
Last Post: snippsat
  python and openCV installation dejhost 16 10,858 Aug-04-2020, 02:23 AM
Last Post: snippsat
  How to detect the text above lines using OpenCV in Python pframe 0 2,525 Apr-14-2020, 09:53 AM
Last Post: pframe
  Developing Python with OpenCV into an Android App AviationFreak 1 6,835 Sep-29-2019, 08:55 AM
Last Post: wavic
  python opencv grayscale conversion error Spandora 1 9,585 May-26-2019, 10:43 AM
Last Post: heiner55
  python variable issues - using spyder and opencv Afrodizzyjack 5 5,819 Jun-19-2018, 09:46 AM
Last Post: gontajones
  Python openCV "img" is not defined error Arontbt 2 8,138 Apr-23-2018, 07:55 PM
Last Post: Arontbt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020