First time posting.
I'm currently trying to use opencv2 in python using virtual studio on M1 macbook air, but for some reason I cannot use the detectMultiScale function? I have completely uninstalled everything and reinstalled everything to no avail. error: (-215) !empty() in function detectMultiScale
For instance:
grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
gets me
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
cv2.error: OpenCV(4.5.1) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-39p1qqfs/opencv/modules/objdetect/src/cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'
Also, I am completely new with using python, so a quick question I have is whether I need to create a virtual environment, activate it, and then pip download opencv2 there? I tried downloading cv2 into just my python file's terminal, but I'm unable to import cv2 there. I'm thinking it might be because the file paths are different? But I have no idea how to use pip installer to a certain file path. I can only import cv2 after installing cv2 inside a venv.
Please advise, thank you!
Before asking this question I've tried :
import cv2
#trained face data import
trained_face_data = cv2.CascadeClassifier('frontfacedetector.xml')
#import my face
img = cv2.imread('Aaron_Prof_Pic.jpg')
#change to grayscale
grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#detecting faces
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
cv2.imshow('why isnt this working', grayscaled_img)
cv2.waitKey()
print("Code completed")
This means that the haarcascade_frontalface_default.xml isn't present in the same directory as of the code or either it's corrupted.
If it's there in the same directory then try using
trained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")
The final code should look somewhat like :
import cv2
trained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")
img = cv2.imread('Aaron_Prof_Pic.jpg')
imgGray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = trained_face_data.detectMultiScale(imgGray)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0,255,0), 2)
cv2.imshow("Face detector", img)
key_press = cv2.waitKey(1)
if key_press == 32: #The ascii code for spacebar
quit()#quits the programme when spacebar is hit
Related
So I'm trying to make simple computer vision app that displays different colored square around your face in live webcam feed.
The problem is when I start the app using vscode terminal my laptop webcam just turns on for some time and then closes but no app window appears?
The error in the terminal:
[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\videoio\src\cap_msmf.cpp (1021) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
Traceback (most recent call last):
File "C:\Users\asher\Downloads\Work\Work Stuff\Python Stuff\Learning Python AI blah blah\Face_Realtime.py", line 23, in <module>
grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
My app's code:
import cv2
from random import randrange
# loading pre-trained data from opencv (haarcascade)
# classifier is just detector
trained_face_data = cv2.CascadeClassifier(
'haarcascade_frontalface_default.xml')
webcam = cv2.VideoCapture(0) # capturing live video
# loop to capture video
while True:
successful_frame_read, frame = webcam.read()
# we need to convert to grayscale before detecting faces
grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# we will detect faces using the line below
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
for (x, y, w, h) in face_coordinates: # loop to show all faces
# create rectangles around face and randrage here creates random colors for rectangles
cv2.rectangle(frame, (x, y), (x+w, y+h), (randrange(128, 256),randrange(128, 256), randrange(128, 256)), 10)
# this is app name for window and taking the img
cv2.imshow('Face Detector', frame)
key = cv2.waitKey(1)
if key==81 or key==113:
break
webcam.release()
print('Trippin through times lol... but code finished')
Try to add if successful_frame_read:, to check whether the frame got successfully read or not. The if statement ensures that only readable frames get processed. This works because the return value of successful_frame_read is a boolean which, as you may guess, tells you if the frame was successfully read. You may need it, because some frames might be corrupt and cause this error.
Your code should look like this:
import cv2
from random import randrange
# loading pre-trained data from opencv (haarcascade)
# classifier is just detector
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
webcam = cv2.VideoCapture(0) # capturing live video
# loop to capture video
while True:
successful_frame_read, frame = webcam.read()
if successful_frame_read: # The newly added if statement
# we need to convert to grayscale before detecting faces
grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# we will detect faces using the line below
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
for (x, y, w, h) in face_coordinates: # loop to show all faces
# create rectangles around face and randrage here creates random colors for rectangles
cv2.rectangle(frame, (x, y), (x+w, y+h), (randrange(128, 256),randrange(128, 256), randrange(128, 256)), 10)
# this is app name for window and taking the img
cv2.imshow('Face Detector', frame)
key = cv2.waitKey(1)
if key==81 or key==113:
break
webcam.release()
print('Trippin through times lol... but code finished')
Fixing the Attribute Error
AttributeError: module 'cv2' has no attribute 'CascadeClassifier'
The issue might be a wrong installation. To ensure, that there are no dependency issues, please install Virtualenv if you haven't already.
Windows:
pip install virtualenv
Install Virtualenv.
cd C:\Users\asher\Downloads\Work\Work Stuff\Python Stuff\Learning Python AI blah blah\ Go to the directory of the project
virtualenv venv Create a virtualenv called venv
venv\Scripts\activate Activate the virtualenv
Install the python packages.
To install OpenCV use pip install opencv-python.
I have a problem here during cropping and saving image by using opencv.
I'm trying to crop by using cv2.SelectROI function but after I drag on the image, cv.2imshow won't work properly.
Here's my code:
import cv2, numpy as np
img = cv2.imread('C:/git/ML/Image/colorful.jpg')
x,y,w,h = cv2.selectROI('img', img, False)
if w and h:
roi = img[y:y+h, x:x+w]
cv2.imshow('cropped', roi)
cv2.moveWindow('cropped', 0, 0)
cv2.imwrite('cropped2.jpg',roi)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(x,y,w,h)
I've tried to change directory in various ways, put imshow method just before selectROI but none of them worked so far.
cv2.imshow itself shouldn't be a problem because when I don't use selectROI and just manually code the cropping performance from start to finish(by defining mouseleftbutton click, drag, leftbuttonup one by one), cv2.imshow, cv2.movewindow and cv2.imwrite works just fine.
also, not confident that the code itself have interal problem because in other computer, those activities(dragging, cropping, open in new window, save) seems to be working just fine.
is there a possibility that i haven't installed sth that should be needed in order to run selectROI..?
Anyways.. any comments will be much appreciated. Plz help me.
I'm trying to run the example from here
import cv2
def viewImage(image):
cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
cv2.imshow('Display', image)
print('test')
cv2.waitKey(0)
cv2.destroyAllWindows()
def grayscale_17_levels (image):
high = 255
while(1):
low = high - 15
col_to_be_changed_low = np.array([low])
col_to_be_changed_high = np.array([high])
curr_mask = cv2.inRange(gray, col_to_be_changed_low,col_to_be_changed_high)
gray[curr_mask > 0] = (high)
high -= 15
if(low == 0 ):
break
image = cv2.imread('ombre_circle.png')
viewImage(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_17_levels(gray)
viewImage(gray)
Whenever I run the code I get the error:
Kernel Restarting
The kernel for main.ipynb appears to have died. It will restart automatically.
I when I comment out these lines:
#cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
#cv2.imshow('Display', image)
the core runs and prints out 'test' and I don't get an error.
I'm using:
Ubuntu-server 18.04
Jupyter lab 1.1.3
opencv-python 4.1.1.26
I run this on a server not on my local environment
I found a workaround for this issue by displaying it with Matplotlib:
def viewImage(image):
plt.subplot(122)
plt.title("RGB")
plt.imshow(image)
plt.show()
image = cv2.imread('img/ombre_circle.png')
viewImage(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_17_levels(gray)
viewImage3(cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB))
However this doesn't solve the issue and takes extra transformations/code so I would like to find a solution to display with opencv.
X11 forwarding is enabled.
I tried opening an SSH connection with the -Y and -C flag (via this question) but this doesn't fix it.
Any ideas what could be the issue?
IPython Github Issue
What I understand from the discussion is that it's a C-level linking or runtime error from the openCV code being run.
I faced the same problem, got solved by using matplotlib SO jupyternb crash
image=cv2.imread("the file")
cv2.imshow("test file", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
I encountered similar issue when I'm loading large tiff files. Same code works for small tiff files. You can look at this post to compress your image then display.
cv2.imshow() would cause Jupyter sessions
to crash: this post of the issue.
As a substitution, please consider using
from google.colab.patches import cv2_imshow on Google Colab.
I am running Anaconda install of python35 with cv2 install from menpo.
I am having trouble with cv2.imshow() inconsistently placing the image window outside of the viewable screen when running code similar to the one below both as a standalone script and line by line in the console (cmd, spyder, ipython)...
import cv2
img = cv2.imread('Image71.jpg',0)
cv2.startWindowThread()
cv2.namedWindow('image')
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
I have also tried the above without cv2.starWindowThread() and cv2.namedWindow() with the same result. The window appears on my taskbar but is not in view, cv2.waitKey(0) responds to the keystroke, and I am not able to bring the window into view using any of the window arrangement shortcut keys for Windows 10 (e.g. alt+tab, Winkey + left, etc).
My OS is Win10 version 1709.
Any help is much appreciated, thx!
img = cv2.imread("test.png")
winname = "Test"
cv2.namedWindow(winname) # Create a named window
cv2.moveWindow(winname, 40,30) # Move it to (40,30)
cv2.imshow(winname, img)
cv2.waitKey()
cv2.destroyAllWindows()
wrapped answer by Kinght in a function for easy calling
def showInMovedWindow(winname, img, x, y):
cv2.namedWindow(winname) # Create a named window
cv2.moveWindow(winname, x, y) # Move it to (x,y)
cv2.imshow(winname,img)
img = cv2.imread('path.png')
showInMovedWindow('named_window',img, 0, 200)
I am using opencv 2.4.11 and python 2.7 for a computer vision project.
I am trying to obtain the SIFT descriptors:
ima = cv2.imread('image.jpg')
gray = cv2.cvtColor(ima,cv2.COLOR_BGR2GRAY)
detector = cv2.FeatureDetector_create('SIFT') # or 'SURF' for that matter
descriptor = cv2.DescriptorExtractor_create('SIFT')
kpts = detector.detect(gray)
When calling the last instruction it throws an ugly segmentation fault. I have to use a 2.4.x version, so uploading to the 3.x version of opencv to use SIFT or SURF methods is not an option. I have downgraded from 3.1 previously using sudo make uninstall and installed from 0 the actual opencv version.
Does anyone have an idea why this happens?
Try:
import cv2
ima = cv2.imread('image.jpg')
gray = cv2.cvtColor(ima, cv2.COLOR_BGR2GRAY)
detector = cv2.SIFT()
kp1, des1 = detector.detectAndCompute(gray, None)
detector = cv2.FeatureDetector_create('SIFT') should also work for creating the SIFT object.
currently I am beginner in Computer Science so apologize for my short explanation.
I have OpenCV 3 and Python 2.7.11
Before all I downloaded no no it's better that you read this site
after all you can write this code (It's almost the same of your code ).
import cv2
import numpy as np
img = cv2.imread('lenna.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
detector = sift.detect(gray, None)
kpts, des = sift.compute(gray, detector)
# kpts,des=descriptor.compute(gray,kpts)
im_with_keypoints = cv2.drawKeypoints(gray, kpts, np.array([]), color=255, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey()
Regards!
Install opencv_contrib using
pip install opencv-contrib-python
Then your code will work.