After referring to some Stack Overflow answers I did pip install opencv-contrib-python, still I am getting those errors.
I am using OpenCV 4.7.0.
This is for a facial recognition project tutorial that I am following.
import cv2
import numpy as np
from PIL import Image
import os
# Path for face image database
path = 'dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
# function to get the images and label data
def getImagesAndLabels(path):
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
faceSamples=[]
ids = []
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L') # grayscale
img_numpy = np.array(PIL_img,'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_numpy)
for (x,y,w,h) in faces:
faceSamples.append(img_numpy[y:y+h,x:x+w])
ids.append(id)
return faceSamples,ids
print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
# Save the model into trainer/trainer.yml
recognizer.write('trainer/trainer.yml')
# Print the numer of faces trained and end program
print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))
I keep getting this error:
File "/Users/sashuponnaganti/workspace/Facial Recognition Project/face_trainer.py", line 7, in <module>
recognizer = cv2.face.LBPHFaceRecognizer_create()
AttributeError: module 'cv2' has no attribute 'face'
Any ideas how to fix this?
I already tried doing pip install opencv-contrib-python and I had already installed it so it made no difference.
This question has been solved. I had installed all my opencv packages in a conda environment but was running it with the wrong interpreter.
Related
I'm trying to load with cv.dnn.readNetFromONNX a pre-trained torch model (U2Net to be precise) saved as onnx.
But I'm receiving the error:
error: OpenCV(4.1.2) /io/opencv/modules/dnn/include/opencv2/dnn/dnn.inl.hpp:349:
error (-204:Requested object was not found) Required argument "starts" not found
into dictionary in function 'get'
This is the code to reproduce the error with Google Colab:
### get U2Net implementation ###
%cd /content
!git clone https://github.com/shreyas-bk/U-2-Net
### download pre-trained model ###
!gdown --id 1ao1ovG1Qtx4b7EoskHXmi2E9rp5CHLcZ -O /content/U-2-Net/u2net.pth
###
%cd /content/U-2-Net
### imports ###
from google.colab import files
from model import U2NET
import torch
import os
### create U2Net model from state
model_dir = '/content/U-2-Net/u2net.pth'
net = U2NET(3, 1)
net.load_state_dict(torch.load(model_dir, map_location='cpu'))
net.eval()
### pass to it a dummy input and save to onnx ###
img = torch.randn(1, 3, 320, 320, requires_grad=False)
img = img.to(torch.device('cpu'))
output_dir = os.path.join('/content/u2net.onnx')
torch.onnx.export(net, img, output_dir, opset_version=11, verbose=True)
### load the model in OpenCV ###
import cv2 as cv
net = cv.dnn.readNetFromONNX('/content/u2net.onnx')
[ OpenCV => 4.1.2, Platform => Google Colab, Torch => 1.11.0+cu113]
As #berak suggestet, the issue was related to the OpenCV version (was 4.1.2). Updating to 4.5.5 solved the issue.
I am working on a project on Python that detects disease on leaves and sprays fertilizer on the leaf.
After many hours of troubleshooting other errors, I came down to the following final error that always happens and I can't seem to fix.
Following are the versions I have used for the dependencies so far:
keras = 2.4.3
cv2 = 4.5.1
numpy = 1.20.1
tensorflow = 2.4.0
h5py = 3.2.1
pandas = 1.2.3
Error that I am facing:
Traceback (most recent call last):
File "leaf_cnn.py", line 12, in <module>
model = load_model('Leaf_CNN.h5')
File "/home/pi/.local/lib/python3.7/site-packages/tensorflow/python/keras/saving/save.py", line 207, in load_model
compile)
File "/home/pi/.local/lib/python3.7/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 182, in load_model_from_hdf5
model_config = json_utils.decode(model_config.decode('utf-8'))
AttributeError: 'str' object has no attribute 'decode'
Code file leaf_cnn.py
# importing files/dependencies
from tensorflow.keras.models import load_model
import cv2
import numpy as np
#import Categories
import time
import RPi.GPIO as GPIO
#loading model/ML algorithm
model = load_model('Leaf_CNN.h5')
cap = cv2.VideoCapture(0) # capture frame
ret, img = cap.read()
channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel,GPIO.OUT)
#cv2.imshow('aaa',img) 'display image with title'
img = cv2.resize(img,(224,224))
img = np.reshape(img,[1,224,224,3])
classes = model.predict(img)
y_pred = np.argmax(classes, axis=1)
y_pred = Categories.categories[int(y_pred)]
if "healthy" not in y_pred:
GPIO.output(21, GPIO.HIGH) #turn-on relay
time.sleep(1)
else:
GPIO.output(21, GPIO.LOW) #turn-off relay
time.sleep(1)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
There seems to be an issue with h5py and it has to be installed in a certain version to ensure compatibility with tensorflow. This is what did the trick for me:
pip uninstall h5py
pip install h5py==2.10.0
I have a model which predicting the steering angle of a car from a picture which I like to implement in a android project by getting the frames from the camera.
in my Python code I'm using a h5 file instead of the tflite file in which the picture is converted to numpy and get processed using Cv2 lib.
Python Code:
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from PIL import Image
import cv2
def img_preprocess(img):
img = img[60:135,:,:]
img = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)
img = cv2.GaussianBlur(img, (3, 3), 0)
img = cv2.resize(img, (200, 66))
img = img/255
return img
if __name__ == '__main__':
model = load_model('model.h5')
image1 = Image.open("Gta2.png")
image1 = np.asarray(image1)
image1 = img_preprocess(image1)
image1 = np.array([image1])
steering_angle = float(model.predict(image1))
if(steering_angle > 0):
print('turn right')
print('turn wheel : {}'.format(steering_angle))
else:
print('turn left')
print('turn wheel : {}'.format(steering_angle))
I've been imported the model.tflite to my project assets and know I need to process the CameraBridgeViewBase.CvCameraViewFrame object from the camera to fit to my model input.
the model input and output.
so my questions are:
How process the CvCameraViewFrame Object as in the python code in the 'img_preprocess' function?
How to reach the input specs?
my android code:
You can first convert your Mat frame to Bitmap, such as the solution in this question.
And then use TFLite Task library ImageClassifier to run the inference. Here is an example of how to use ImageClassifier, which comes from the TFLite Image Classification reference app.
Alternatively, you can write your own code to process the image and run inference using Interpreter. See the example here.
I wanted to use the flask-opencv-streamer python package but cannot seem to find a workaround on how to import it.
If i use the example code at here: https://pypi.org/project/flask-opencv-streamer/#description , I will get an import error and in case if I change the '_' to '-',it gives syntax error.
from flask-opencv-streamer.streamer import Streamer
import cv2
port = 3030
require_login = False
streamer = Streamer(port, require_login)
# Open video device 0
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
streamer.update_frame(frame)
if not streamer.is_streaming:
streamer.start_streaming()
cv2.waitKey(30)
I have a problem with face detection.
code:
import cv2
import os
import numpy as np
from PIL import Image
path = 'dataSet'
cascadePath = "Classifiers/face.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
cam = cv2.VideoCapture(0)
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.load('trainer/trainer.yml')
AttributeError:
'cv2.face_LBPHFaceRecognizer' object has no attribute 'Load'
Help me, I already researched and still have not found an answer.
I am using python 3.6.1 and opencv 3.0
That's because it doesn't have that property. You mean read.
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
Here's the help:
| read(...)
| read(filename) -> None
| . #brief Loads a FaceRecognizer and its model state.
| .
| . Loads a persisted model and state from a given XML or YAML file . Every FaceRecognizer has to
| . overwrite FaceRecognizer::load(FileStorage& fs) to enable loading the model state.
| . FaceRecognizer::load(FileStorage& fs) in turn gets called by
| . FaceRecognizer::load(const String& filename), to ease saving a model.