VIDEOIO(CV_IMAGES): raised OpenCV exception: - python

When I run the code, I got this error:
[ERROR:0] global /io/opencv/modules/videoio/src/cap.cpp (116) open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.1.2) /io/opencv/modules/videoio/src/cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'icvExtractPattern'
Please show me how to fix it. Thank you very much.
And this is my source code:
# Program for finding the location of a person based a difference images
# The video file name should be specified.
import os
from typing import Dict, List, Tuple
import datetime
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
#import sklearn
#from sklearn import metrics
#from sklearn import neural_network
#import sklearn_util
import cv2
def guess_location(src):
index = np.array([i for i in enumerate(src)])
index_sum_sort10 = index[index[:, -1].argsort()][::-1][0:40].T
location = int(np.average(index_sum_sort10[0]))
return location
def calculate_location(src):
row_max_location = guess_location(np.sum(src, axis=0))
col_max_location = guess_location(np.sum(src, axis=1))
return (row_max_location, col_max_location)
#
# Read video frames from a usb-camera / video file,
# and find the location of the person
#
cap = cv2.VideoCapture(0)
v_filename= '/dev/compact-module/Videodata/2021/03/22/1720_00_006686/entity_video_1616401200006.mp4'
#'/media/qf-zhao/68A01144A0111A60/GrayDiffVideo/Image2019_11_18_08_40_00.avi'
cap = cv2.VideoCapture(v_filename)
th_change = 150
th_value = 30
location_back=(0,0)
while(cap.isOpened()):
ret, frame = cap.read()
diff=cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
diff[diff<th_value]=0
if np.max(frame) < th_change:
location=location_back
else:
location = calculate_location(diff)
print("location:", location)
cv2.circle(frame, location, 10, (0,0,255), -1)
cv2.imshow('Result image', frame)
location_back=location
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()

Related

TypeError: only size-1 arrays can be converted to Python scalars (cv2, template matching)

I'm trying to use cv2 for template matching on a screen recording, but am running into an error that is telling me:
TypeError: only size-1 arrays can be converted to Python scalars
Source Code:
import numpy as np
from PIL import ImageGrab
import cv2
import time
import pandas
def screen_record():
last_time = time.time()
template = cv2.imread('C:\\Users\\Bran\\Pictures\\ovw_focus_point.jpg',-1)
while(True):
printscreen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
print((time.time()-last_time))
last_time = time.time()
img = cv2.imread('window',cv2.cvtColor(printscreen, cv2.COLOR_BGR2GRAY))
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF)
print(res)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
if __name__ == "__main__":
screen_record()
Hoping someone can help!

Getting No module named 'picamera' while running FaceRecognition code in Python on RaspberryPi

I am running my Python FaceRecognition code on RaspberryPi but I am getting No module named 'picamera' error. I have tried few solutions but none worked for me. Can someone please figure out what is the problem?
Below is my Python Code:
import cv2
import numpy as np
from imutils.video.pivideostream import PiVideoStream
from imutils.video import FPS
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import argparse
import imutils
#Load pretrained cascade face detection
face_cascade = cv2.CascadeClassifier('lbpcascade_frontalface.xml')
#Load improved FPS video instead of the default Picamera
reader = PiVideoStream().start()
time.sleep(0.2)
#Load the recognizer
rec = cv2.face.createLBPHFaceRecognizer()
#Load trained local binary pattern face data
rec.load("recognizer/trainingData.yml")
id=0
font = cv2.FONT_HERSHEY_SIMPLEX
#Face recognition function
def detectFace(faces,hog,img):
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
result = cv2.face.MinDistancePredictCollector()
rec.predict(hog[y:y+h,x:x+w],result, 0)
id = result.getLabel()
conf = result.getDist()
if(conf<150):
if(id==1):
id="Ibrahim_"+str(conf)
elif(id==2):
id="Minh_"+str(conf)
else:
id="Hyeon_"+str(conf)
else:
id="Unknow"
cv2.putText(img,str(id),(x,y+h),font,1,(255,255,255),2,cv2.LINE_AA)
while(True):
#read each frame in the real-time video
frame = reader.read()
img=frame
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Use histogram equalizer for adjusting face in different light condition
equ = cv2.equalizeHist(gray)
faces = face_cascade.detectMultiScale(equ, 1.05, 5,minSize=(10,10))
#If the face is not frontal face then rotate the face by +30/-30 degree
if len(faces)==0:
rows,cols = equ.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),30,1)
dst = cv2.warpAffine(equ,M,(cols,rows))
faces = face_cascade.detectMultiScale(dst, 1.05, 5,minSize=(10,10))
if len(faces)==0:
rows,cols = equ.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),-30,1)
dst = cv2.warpAffine(equ,M,(cols,rows))
faces = face_cascade.detectMultiScale(dst, 1.05, 5,minSize=(10,10))
detectFace(faces,dst,img)
else:
detectFace(faces,dst,img)
else:
detectFace(faces,equ,img)
cv2.imshow('Face', img)
if(cv2.waitKey(1)==ord('q')):
break;
cap.release()
cv2.destroyAllWindows()
Below is what I run on RaspberryPi terminal and what I get:
(cv) pi#raspberrypi:~/Downloads/Raspberry_pi_face_recognition-master $ python FaceRecognizer.py
Traceback (most recent call last):
File "FaceRecognizer.py", line 3, in <module>
from imutils.video.pivideostream import PiVideoStream
File "/home/pi/.virtualenvs/cv/lib/python3.5/site-packages/imutils/video/pivideostream.py", line 2, in <module>
from picamera.array import PiRGBArray
ImportError: No module named 'picamera'
Just Try it for python3
sudo apt install python3-picamera
sudo -H pip3 install --upgrade picamera[array]
In code file write this steps:
from picamera import PiCamera
camera = PiCamera()
and must be ensure that camera = PiCamera() line is not be in loop.

Background Object detection in face recognition Using OpenCV

I have created a face recognition code using OpenCV. Now the problems occuring are :
-> Sometimes it detects small objects from the wall and show them as me. How can i stop it from doing so ? so that it only detect faces not objets.
-> Whenever a unknown person shows up on scree, it randomly shows any name to it from the database. I waant it to show as a Unknown Face whenever someone unknown hits the cam.
Note : i did not added it to sql database yet but will do it after i get through this.THanks for the help in advance
Data Set creator code:
import cv2
import sqlite3
import numpy as np
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
cam=cv2.VideoCapture(0);
id = raw_input('Enter Your ID : ')
Name = raw_input('Enter Your Name : ')
sampleNum=0;
while(True):
ret,img=cam.read();
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
sampleNum=sampleNum+1;
cv2.imwrite("dataSet/User."+str(id)+"."+str(sampleNum)+".jpg",gray[y:y+h,x:x+w])
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.waitKey(500);
cv2.imshow("Face",img);
cv2.waitKey(1);
if(sampleNum>20):
break;
cam.release()
cv2.destroyAllWindows()
Trainer Code :
import os
import cv2
import numpy as np
from PIL import Image
recognizer=cv2.createLBPHFaceRecognizer();
path='dataSet'
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
faceImg=Image.open(imagePath).convert('L');
faceNp=np.array(faceImg,'uint8')
ID=int(os.path.split(imagePath)[-1].split('.')[1])
faces.append(faceNp)
print ID
IDs.append(ID)
cv2.imshow("training",faceNp)
cv2.waitKey(10)
return IDs, faces
Ids,faces=getImagesWithID(path)
recognizer.train(faces,np.array(Ids))
recognizer.save('recognizer/trainningData.yml')
cv2.destroyAllWindows()
Detector Code :
import cv2
import numpy as np
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
cam=cv2.VideoCapture(0);
rec=cv2.createLBPHFaceRecognizer();
rec.load("recognizer\\trainningData.yml")
id=0
font=cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_COMPLEX_SMALL,2,2,0,2)
while(True):
ret,img=cam.read()
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
id,conf=rec.predict(gray[y:y+h,x:x+w])
if(id==1):
id="Vivek"
cv2.cv.PutText(cv2.cv.fromarray(img),str(id),(x,y+h),font,255);
cv2.imshow("Face",img);
if(cv2.waitKey(1)==ord('q')):
break;
cam.release()
cv2.destroyAllWindows()

RuntimeError: Expected writable numpy.ndarray with shape set

I try to load some images into an RDD and use the face recognition library(https://github.com/ageitgey/face_recognition) to compare different images. Following code work
import face_recognition
import numpy as np
from io import BytesIO
from PIL import Image
from pyspark import SparkContext
sc = SparkContext(appName="LoadingImage")
images = sc.binaryFiles("./images/")
image_to_array = lambda rawdata: np.asarray(Image.open(BytesIO(rawdata)))
i_arr = images.values().map(image_to_array)
new_encoding = face_recognition.face_encodings(i_arr.first())
next_encoding = face_recognition.face_encodings(i_arr.first())
result = face_recognition.compare_faces([new_encoding[0]], next_encoding[0])
print(result)
However, when I try to map face_encodings function to all the elements inside the RDD, it always gives me an error:
RuntimeError: Expected writable numpy.ndarray with shape set.
img_to_encodings = lambda img: face_recognition.face_encodings(img)[0]
i_arrm = i_arr.map(img_to_encodings)
result = face_recognition.compare_faces([i_arrm.first()], i_arrm.first())
print(result)
The error is from dlib library, but I reckon I did something wrong with spark. Any idea how to solve this?
The frame returned by picamera has flag set to false i.e Writable : False.
Set frame flag to true so that face_recognition package can use it. Code Snippet:
image.setflags(write=True)
For Demo Code Have A Look:
#import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
#initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
#allow the camera to warmup
time.sleep(0.1)
#capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image = frame.array
image.setflags(write=True)
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
# if the q key was pressed, break from the loop
if key == ord("q"):
break
cv2.destroyAllWindows()

Issue With Opencv Face Detection

I have been trying to get the openCV 2.4.13 python27 face Detection from images please help.The error that I get is:
Traceback (most recent call last):
File "C:\Users\sam_o\Desktop\Alrehman\Attendance.py", line 36, in <module>
profile = getProfile(id)
File "C:\Users\sam_o\Desktop\Alrehman\Attendance.py", line 19, in getProfile
profile = none
NameError: global name 'none' is not defined
The code I wrote is as follows:
import cv2,os
import numpy as np
from PIL import Image
import pickle
import sqlite3
recognizer = cv2.createLBPHFaceRecognizer()
cascadePath = "Classifiers/face.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
path = 'EmployeeRecord'
def getProfile(id):
conn=sqlite3.connect("Alrehman.db")
cmd="SELECT * FROM Person WHERE ID="+str(id)
cursor=conn.execute(cmd)
profile=none
for row in cursor:
profile=row
conn.close()
return profile
cam = cv2.VideoCapture(0)
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) #Creates a font
while True:
ret, im =cam.read()
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
faces=faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE)
for(x,y,w,h) in faces:
id, conf = recognizer.predict(gray[y:y+h,x:x+w])
cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
profile=getProfile(id)
if(profile!=None):
cv2.cv.PutText(cv2.cv.fromarray(im),str(profile[1]), (x,y+h+30),font, 255) #Draw the text
cv2.cv.PutText(cv2.cv.fromarray(im),str(profile[2]), (x,y+h+60),font, 255) #Draw the text
cv2.imshow('im',im)
cv2.waitKey(10)
Does anyone have any idea what I might be doing wrong here?
It looks like either your camera is not capturing a photo, or capturing a grayscale photo. (error code 215 is common in such cases, in other opencv functions as well)
You can test this further by loading a sample image from the computer, and passing that to cv2.cvtColor().
I tried it This is code is working for me.....
import cv2
import numpy as np
import os
import pickle
import sqlite3
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
def getProfile(id):
conn=sqlite3.connect("FaceBase.db")
cmd="SELECT * FROM People WHERE ID="+str(id)
cursor=conn.execute(cmd)
profile=None
for row in cursor:
profile=row
conn.close()
return profile
cam=cv2.VideoCapture(0);
rec=cv2.createLBPHFaceRecognizer();
rec.load("recognizer\\trainner.yml");
id=0
font=cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_COMPLEX_SMALL,1,1,0,1)
while(True):
ret,img=cam.read();
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
id,conf=rec.predict(gray[y:y+h,x:x+w])
profile=getProfile(id)
if(profile!=None):
cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[1]),(x,y+h+30),font,255);
cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[2]),(x,y+h+60),font,255);
cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[3]),(x,y+h+90),font,255);
# cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[4]),(x,y+h+30),font,255);
cv2.imshow("Face",img);
if(cv2.waitKey(1)==ord('q')):
break;
cam.release();
cv2.destoryAllWindows()

Categories

Resources