i would like to detect faces with mask, here is one example of image :
classical side face detector
faceCascade =cv2.CascadeClassifier("haarcascade_profileface.xml")
does not detect faces well, therefore i tried to search a little more and found following documentation :
yunet documentation
i have tried to implement this model in my code :
import numpy as np
import matplotlib.pyplot as plt
import cv2
import math
#faceCascade =cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
#faceCascade =cv2.CascadeClassifier("haarcascade_profileface.xml")
frame =cv2.imread("distance_Measure.jpg")
frame =cv2.resize(frame,(500,500))
gray =cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
face_detector = cv2.FaceDetectorYN_create("yunet.onnx", "", (0, 0))
#faces =faceCascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,minSize=(20,20))
_, faces = face_detector.detect(gray)
l =[]
lf =[]
i =1
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
s =str(i)
cv2.putText(frame,s,(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)
i+=1
l =[]
l.append(x)
l.append(y)
lf.append(l)
print(l)
print(lf)
close_person =""
for i in range(len(lf)):
for j in range(i+1,len(lf)):
d =math.sqrt((lf[j][1]-lf[i][1])**2+((lf[j][0]-lf[i][0])**2))
print("P",i+1,"-P",j+1,"=",d)
if d <150:
close_person ="Person " +str(i+1)+" and Person "+str(j+1)+";"
cv2.line(frame,(lf[i][0],lf[i][1]),(lf[j][0],lf[j][1]),(0,0,255),2)
close_person+=" are not following social distance"
print(close_person)
cv2.imshow("Displayed_Persons",frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
plt.show()
but it returns following error :
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\AI_Project\Social_Distance_Measurement_Example.py", line 10, in <module>
face_detector = cv2.FaceDetectorYN_create("yunet.onnx", "", (0, 0))
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\onnx\onnx_importer.cpp:194: error: (-5:Bad argument) Can't read ONNX file: yunet.onnx in function 'cv::dnn::dnn4_v20211220::ONNXImporter::ONNXImporter'
i have searched again and found following documentation :
searched solution
but i could not clarify how to solve given problem, please help me
Related
I have the following little code:
from google.colab import drive
from IPython.display import display
import PIL
from PIL import Image, ImageDraw
import kraken
from kraken import pageseg
import cv2 as cv
img = Image.open("/content/drive/My Drive/images/dropfire.jpg")
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + "/content/drive/My Drive/datas/haarcascade_frontalface_default.xml")
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + "/content/drive/My Drive/datas/haarcascade_eye.xml")
file_name = "/content/drive/My Drive/images/dropfire.jpg"
img = cv.imread(file_name)
pil_img = Image.open(file_name)
cv_img = pil_img.convert('L')
cv_img = cv.imread(file_name)
faces = face_cascade.detectMultiScale(cv_img)
When I run the last cell (with faces), it raises:
error Traceback (most recent call last)
<ipython-input-23-2bd7582f8a20> in <module>()
----> 1 faces = face_cascade.detectMultiScale(cv_img)
error: OpenCV(4.1.2) /io/opencv/modules/objdetect/src/cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'
Until this cell everything works fine. According to a Stack Overflow answer, I added cv.data.haarcascades + in the brackets of cv.CascadeClassifier. Although people said this worked for them, it doesn't for me somehow.
imho, that "little code" of yours has too much noise (unnecessary lines of code) already.
I think it makes for you even harder to understand what's going on.
Comment out/delete all the lines except these:
import cv2 as cv
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_eye.xml")
file_name = "/content/drive/My Drive/images/dropfire.jpg"
img = cv.imread(file_name) # this reads the image already
cv_img = cv.imread(file_name) # this reads same image once more, not sure if intended
faces = face_cascade.detectMultiScale(cv_img)
If your image "dropfire" really exists at that path, this should work without error, but it won't show any results of face detection. You can add these lines at the end to see the result:
for (x, y, w, h) in faces:
cv.rectangle(cv_img, (x, y), (x+w, y+h), (0, 0, 255), 3)
cv.imshow("Nice face", cv_img)
cv.waitKey(0)
cv.data.haarcascades already has path to all those cv2 xml files, so you only need to use file names.
The issue is to check whether XML is loaded or not, use
eye_cascade.empty() to check whether it's loaded or not.
This is my code for building a linear classifier for images and cv2.resize() is throwing error while converting the image from original size to (32,32)
import numpy as np
import cv2
labels = ["dog","cat","panda"]
np.random.seed(1)
W = np.random.randn(3,3072)
b = np.random.randn(3)
orig = cv2.imread("panda_00001.png")
image = cv2.resize(orig,(32,32)).flatten()
scores = W.dot(image) + b
for (label,score) in zip(labels,scores):
print("[INFO] {}:{:.2f}".format(label,score))
cv2.putText(orig,"Label:{}".format(labels[np.argmax(scores)]),(10,30),cv2.FONT_HERSHEY_SIMPLEX,0.9,(0,255,0),2)
cv2.imshow("Image",orig)
cv2.waitkey(0)
Getting this error on execution
Traceback (most recent call last):
File "linearclassifier.py", line 11, in <module>
image = cv2.resize(orig,(32,32)).flatten()
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:3929: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
Your picture path seems to be wrong or invalid.
It's always good practice to integrate a null check to the read picture in your script:
eg:
import cv2
...
img = cv2.imread("myImage.jpg")
if (img.size == 0):
# error handling or throw exception here!
# do stuff with image here
I am trying to apply cv2.createBackgroundSubtractorMOG() to this Image:
to eliminate all background brightness and only leave the two bright objects in the middle for further analysis. Is this the right approach for this task? If not, how would I do that?
import cv2
img = cv2.imread('image.png')
sharp_img = cv2.createBackgroundSubtractorMOG().apply(img)
Output:
Traceback (most recent call last):
File "/home/artur/Desktop/test.py", line 4, in <module>
sharp_img = cv2.createBackgroundSubtractorMOG().apply(img)
AttributeError: module 'cv2.cv2' has no attribute 'createBackgroundSubtractorMOG
Edit:
MOG does not seem to work.
Code:
import cv2
img = cv2.imread('image.png')
sharp_img = cv2.bgsegm.createBackgroundSubtractorMOG().apply(img)
cv2.imwrite('image2.png', sharp_img)
Output:
Traceback (most recent call last):
File "/home/artur/Desktop/test.py", line 4, in <module>
sharp_img = cv2.bgsegm.createBackgroundSubtractorMOG().apply(img)
AttributeError: module 'cv2.cv2' has no attribute 'bgsegm'
MOG2 seems to work but with no satisfying result:
Code:
import cv2
img = cv2.imread('image.png')
sharp_img = cv2.createBackgroundSubtractorMOG2().apply(img)
cv2.imwrite('image2.png', sharp_img)
Output Image:
I tried to play around with the args of the MOG2 Method from the docs but with no change.
from the docs, try this:
sharp_img = cv.bgsegm.createBackgroundSubtractorMOG().apply(img)
or
sharp_img = cv2.createBackgroundSubtractorMOG2().apply(img)
import cv2
img = cv2.imread('image.png')
max,min = img.max(),imgg.min()
print(max,min) #helps in giving thresholding values
threshold_img = cv2.threshold(blurred, 127, 255,cv2.THRESH_BINARY) #good starting point to give t1 value as half of max value of image
cv2.imshow(threshold_img)
This approach is a good starting point in your case, as you have two bright peaks that you want to separate from the noise. Once you have identified the required threshold limits, you should be able to isolate the two spots from the noise in the background. You can further use cv2.erode and cv2.dilate if needed to remove further noise.
Here i'm trying to:
- Apply Adaptive filtering to image .
- Enhance the contrast of image .
my code is as follow :
#!/usr/bin/python
import cv2
import numpy as np
import PIL
from PIL import ImageFilter
from matplotlib import pyplot as plt
img = cv2.imread('Crop.jpg',0)
cv2.imshow('original',img)
img = cv2.medianBlur(img,5)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
cv2.imshow('image',th3)
th3 = th3.filter(ImageFilter.SMOOTH)
cv2.imshow('image',th3)
cv2.waitKey(0)
cv2.destroyAllWindows()
I am getting following Error :
Traceback (most recent call last):
File "./adaptive.py", line 22, in
th3 = th3.filter(ImageFilter.SMOOTH)
AttributeError: 'numpy.ndarray' object has no attribute 'filter
You may confuse with cv.Smooth
this is the basic code from opencv-python documentation:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('simple.jpg',0)
# Initiate STAR detector
orb = cv2.ORB()
# find the keypoints with ORB
kp = orb.detect(img,None)
# compute the descriptors with ORB
kp, des = orb.compute(img, kp)
# draw only keypoints location,not size and orientation
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
plt.imshow(img2),plt.show()
and it gives me this error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 18, in <module>
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
error: ..\..\..\..\opencv\modules\features2d\src\draw.cpp:115: error: (-215) !outImage.empty() in function cv::drawKeypoints
i have to mention this error happens in opencv-PYTHON, can you help me out please? struggling really to make it work
i've found the solution
it couldn't find the image
i changed
img = cv2.imread('simple.jpg',0)
to
img = cv2.imread('c:\\python27\\sample.jpg', cv2.IMREAD_GRAYSCALE)
and it worked
note that the image i used for the sample image was one of my own grayscale images.