hasanthecoder
hasanthecoder

Reputation: 91

Cannot turn on Mac Webcam through OpenCV python

I am new to opencv and trying to access my Macbook's built-in camera through OpenCV python but it gives an error.

import cv2

frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)

while True:
   success, img = cap.read()
   cv2.imshow("Result", img)
   if cv2.waitKey(1) & 0xFF == ord('q'):
       break

Traceback (most recent call last):
  File "/Users/hasanaktas/PycharmProjects/OpencvPython/project3.py", line 12, in <module>
    cv2.imshow("Result", img)
cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

already tried changing VideoCapture(0) to VideoCapture(1) and adding the following code but still didn't help. Btw using PyCharm

cap.release()
cv2.destroyAllWindows()

Upvotes: 9

Views: 21773

Answers (4)

Mostafa Othman
Mostafa Othman

Reputation: 1

Try to increase frame width/height, for example use:

frameWidth = 1048 frameHeight = 1028

Upvotes: -2

pani3610
pani3610

Reputation: 113

I had the same issue on my Mac. I simply replaced

cv2.VideoCapture(0)

with

cv2.VideoCapture(1)

works like a charm.

Upvotes: 10

Abbasihsn
Abbasihsn

Reputation: 2171

I had the same problem and I did not find any solution. By trial and error, I found that my OpenCV version is corrupted. As a result, I deleted it and install a new fresh one. You can use one of these two options: 1. Terminal run brew uninstall opencv3 to uninstall opencv then install it using sudo apt-get install libopencv-dev python-opencv command.

2. Anaconda Actually, I used this method for my own problem.

  1. open anaconda
  2. go to the environment section and select your environment as follow: enter image description here then click on installed and search for opencv: enter image description here select opencv package and uninstall it. then try to re-install opencv by selecting not installed and searching for opencv. be careful to install the correct version. enter image description here

Upvotes: 0

Ahx
Ahx

Reputation: 7985

There are two suggestions I would like to mention.

#1: Enable your terminal or PyCharm to reach the camera.


  • Go to System Preferences-> Security and Privacy -> Camera and add PyCharm to the list.

    • enter image description here

#2 Instead of while True use while cap.isOpened(), so you can know that PyCharm or terminal can access your camera.

  • import cv2
    
    frameWidth = 640
    frameHeight = 480
    cap = cv2.VideoCapture(0)
    cap.set(3, frameWidth)
    cap.set(4, frameHeight)
    cap.set(10,150)
    
    while cap.isOpened():
        success, img = cap.read()
        if success:
            cv2.imshow("Result", img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    

Upvotes: 8

Related Questions