182 error 215 assertion failed src empty in function cv cvtcolor

I am trying to do a basic colour conversion in python however I can't seem to get past the below error. I have re-installed python, opencv and tried on both python 3.4.3 (latest) and python 2.7 (wh...

must please see guys that the error is in the cv2.imread() .Give the right path of the image. and firstly, see if your system loads the image or not. this can be checked first by simple load of image using cv2.imread().
after that ,see this code for the face detection

import numpy as np
import cv2

cascPath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-   packages/cv2/data/haarcascade_frontalface_default.xml"

eyePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml"

smilePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml"

face_cascade = cv2.CascadeClassifier(cascPath)
eye_cascade = cv2.CascadeClassifier(eyePath)
smile_cascade = cv2.CascadeClassifier(smilePath)

img = cv2.imread('WhatsApp Image 2020-04-04 at 8.43.18 PM.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, cascPath ,eyePath ,smilePath should have the right actual path that’s picked up from lib/python3.7/site-packages/cv2/data here this path should be to picked up the haarcascade files

my code:

import cv2

face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)

eye_cascade = cv2.CascadeClassifier(‘haarcascade_eye.xml’)

cap = cv2.VideoCapture(0)

while True:

ret, color_img = cap.read()
gray_image = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray_image)
for (x,y,w,h) in faces :

    cv2.rectangle(color_img,(x,y) , (x+w,y+h) , (255,0,0), 2)
    face_gray = gray_image[y:y+h , x:x+w]
    face_color = color_img[y:y+h , x:x+w]

    eyes = eye_cascade.detectMultiScale(face_gray)
    for (ex,ey,ew,eh) in eyes :
        cv2.rectangle(face_color,(ex,ey),(ex+ew,ey+eh),(0,255,0), 2)

        cv2.imshow('img',color_img)

        k = cv2.waitKey(30) & 0xff

        if k == 113:
            break

        cap.release()
        cv2.destroyAllWindows()

how to fix this error:

error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

ret, color_img = cap.read()
gray_image = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

faces = face_cascade.detectMultiScale(gray_image)
for (x,y,w,h) in faces :

    cv2.rectangle(color_img,(x,y) , (x+w,y+h) , (255,0,0), 2)
    face_gray = gray_image[y:y+h , x:x+w]
    face_color = color_img[y:y+h , x:x+w]
   
   eyes_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

    eyes = eye_cascade.detectMultiScale(face_gray)
    for (ex,ey,ew,eh) in eyes :
        cv2.rectangle(face_color,(ex,ey),(ex+ew,ey+eh),(0,255,0), 2)

        cv2.imshow('img',color_img)

        k = cv2.waitKey(30) & 0xff

        if k == 113:
            break

        cap.release()
        cv2.destroyAllWindows()

This should work

Содержание

  1. [Solved] cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’
  2. How cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error Occurs ?
  3. How To Solve cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error ?
  4. Solution 1: Check Image path
  5. Solution 2: wrong image location
  6. Solution 3: Give Full Path
  7. Summary
  8. OpenCV Error: Failed Assertion #2
  9. Comments

[Solved] cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

Hello Guys, How are you all? Hope You all Are Fine. Today I am just trying to read image through cv2 in my code and I am facing following error cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error Occurs ?

I am just trying to read image through cv2 in my code and I am facing following error.

How To Solve cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error ?

  1. How To Solve cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error ?

To Solve cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error Please check image path. This error usually occurs when image is not loaded correctly in any way. Second solution is You might given wrong image location. Or esle try to assign diffrent path. Third Solution is I just give full path and that was worked for me.
cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

To Solve cv2.error: OpenCV(4.5.2) color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’ Error Please check image path. This error usually occurs when image is not loaded correctly in any way. Second solution is You might given wrong image location. Or esle try to assign diffrent path. Third Solution is I just give full path and that was worked for me.

Solution 1: Check Image path

Please check image path. This error usually occurs when image is not loaded correctly in any way.

Here is how this error occurs.

Try to giving the image address directly; something like

Solution 2: wrong image location

You might given wrong image location. Or esle try to assign diffrent path.

Solution 3: Give Full Path

I just give full path and that was worked for me.

Summary

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Источник

OpenCV Error: Failed Assertion #2

Receiving the following error: OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
Traceback (most recent call last):
File «/home/pi/rpotter.py», line 138, in FindWand
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor

Using the Pi NoIR. Still searching for a solution.

The text was updated successfully, but these errors were encountered:

I am running in the virtual environment.
I just tried outside of the virtual enviroment and now get a different error:

warnings.filterwarnings(«ignore», category=np.VisibleDeprecationWarning)
AttributeError: ‘module’ object has no attribute ‘VisibleDeprecationWarning’

Can you check your numpy version both inside and outside the virtual environment?

python -c «import numpy; print numpy.__version__»

I am also having the same issue as TEEPLE31. And I am also in virtual environment when trying. I will also check my numpy versions.

I have 1.8.2 in both environments

Initializing point tracking
START switch_pin ON for pre-video test
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
Error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor

START incendio_pin ON and set switch off if video is running
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp, line 8000
No points found
Tracking Error:

(Raspberry Potter:1189): GLib-GObject-CRITICAL **: g_object_unref: assertion ‘G_IS_OBJECT (object)’ failed

(Raspberry Potter:1189): GLib-GObject-CRITICAL **: g_object_unref: assertion ‘G_IS_OBJECT (object)’ failed
Tracking Error:

Ok — I’m rebuilding so I can dig into this. right now I’m thinking this is related to the virtual environment and the OpenCV python bindings.

Everything I am reading is that OpenCV and PiCamera do not play well together.

— Just remembered to check my python instance outside of the virtual env.

Outside of virtual env:
$ python 3.4

import cv2
ImportError: No module named ‘cv2’

Inside virtual env:
$ python #python3.4

Import error no module named cv2.

Problem solved for me. Need to make sure I am running python2.7 in virtual env.

$ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2
Type «help», «copyright», «credits» or «license» for more information.

import cv2
Traceback (most recent call last):
File «», line 1, in
ImportError: No module named cv2

[1]+ Stopped python
pi@raspberrypi:

$ source /.profile
pi@raspberrypi: $ workon cv
(cv) pi@raspberrypi:

$ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2
Type «help», «copyright», «credits» or «license» for more information.

Try:
$ sudo modprobe bcm2835-v4l2

/.profile
$ workon cv
—assuming you are now in virtual env—
$ sudo pigpiod
$ sudo modprobe bcm2835-v4l2
$ python2.7 rpotter.py

/.profile $ workon cv —assuming you are now in virtual env— $ sudo pigpiod $ sudo modprobe bcm2835-v4l2 $ python2.7 rpotter.py — You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.

I am also getting a similar error.
Initializing point tracking
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-3.2.0/modules/imgproc/src/color.cpp, line 9748
Error: /home/pi/opencv-3.2.0/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/pi/opencv-3.2.0/modules/imgproc/src/color.cpp, line 9748
Traceback (most recent call last):
File «rpotter.py», line 204, in
TrackWand()
File «rpotter.py», line 133, in TrackWand
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/pi/opencv-3.2.0/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor

sudo modprobe bcm2835-v4l2 fixed the first error, but I am not sure what to do about the 2nd error.

Anyone have any other ideas on how to fix it?

Python 2.7
Is it a problem with the version?

Anyone figure out this issue, same as sallyliest over here

A friend of mine figured it out and we got it to work.
I just had to comment out line 250: cam.release()
I also did what teeple3 said to do.

Also make sure you use the code that’s in the ollivanderslamp folder.

I ran into a couple other issues with linking the python modules so if you had a problem with that just lmk.

I’ve been working on this damn lamp for so long, and have finally gotten far enough to even understand how to follow your instructions. I have just gotten picture and tracking marks up on the pi via ssh and and pretty proud of myself, but of course I could have done none of it without you sharing your knowledge and experience. Thanks to you, my daughter will have her harry potter lamp under the tree this xmas.

Источник

Explanation of the problem

The program is encountering an error when attempting to run the following line of code:

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

The error message being displayed is:

cv2.error: OpenCV(4.1.0) C:projectsopencv-pythonopencvmodulesimgprocsrccolor.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

This error is indicating that the “cvtColor” function from the OpenCV library is encountering an assertion failure because the input image, “im”, is empty. This is likely causing the program to crash.

The error message is coming from the OpenCV library, which is being used to perform image processing tasks. The specific function that is causing the error is “cvtColor”, which is used to convert an image from one color space to another. In this case, the code is attempting to convert the “im” variable from the BGR color space to the grayscale color space.

The error message is indicating that an assertion failure is occurring within the “cvtColor” function. This is likely due to the “im” variable being empty, which is causing the function to fail. The assertion failure is triggered by the following line of code:

CV_Assert(!_src.empty());

This line of code is checking if the input image is empty, and if it is, the program is terminated with the error message.

To solve this problem, the cause of the empty input image must be identified and addressed. This could be due to a variety of reasons, such as the image not being properly loaded or initialized. One possible solution is to check the value of the “im” variable before passing it to the “cvtColor” function, to ensure that it is not empty. Another solution would be to check the path of the image and make sure it is correct and accessible. It is also possible that the image file is corrupted or missing, in this case, the correct image file needs to be located and added to the project.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for cv2.error: OpenCV(4.1.0) C:projectsopencv-pythonopencvmodulesimgprocsrccolor.cpp:182: error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

An “empty image” error in image processing refers to a situation where the image being processed did not load successfully. This can happen when the image data is not being properly read or when the image file does not exist. This issue can be caused by a variety of factors such as a failed camera connection or incorrect configuration.

One possible cause of this error is an issue with the code being used to capture the image. For example, in the case of using the OpenCV library in Python, the following code snippet may be used to capture an image from a camera:

import cv2

cap = cv2.VideoCapture(1)
ret, frame = cap.read()

Here, the cv2.VideoCapture() function is used to initialize a video capturing object, and the integer parameter passed to it specifies the index of the camera to be used. In the case above, the index 1 is passed, indicating that the second camera on the system is to be used. However, if the camera is not connected or is not configured correctly, this may result in an “empty image” error.

A solution to this problem may be to check and adjust the code being used to capture the image. For example, in this case, the error was resolved by changing “cap = cv2.VideoCapture(1)” to “cap = cv2.VideoCapture(0)”. This suggests that the error may have been related to OpenCV interpreting the fingerprint input as a camera. By changing the index passed to the cv2.VideoCapture() function, the program is now using the first camera on the system. Additionally, you can check the return value of the read method, it should be True if it is able to read an image.

import cv2

cap = cv2.VideoCapture(0)
ret, frame = cap.read()
if ret==True:
    # image is read successfully
else:
    # empty image error

It is important to test the code with different camera indices and configurations to ensure that the correct camera is being used and that the image is being captured correctly.

Other popular problems with Ageitgey face-recognition

Problem: False Positive Identification

One of the most common problems with facial recognition systems is the issue of false positives. This occurs when the system incorrectly identifies a person as someone else. This can be caused by a variety of factors, such as poor lighting conditions, low-resolution images, or the presence of facial obstructions (e.g. glasses or hats).

Solution:

One way to reduce the number of false positives is to use a more robust feature extraction algorithm. For example, instead of using simple edge detection to identify facial features, a more advanced algorithm such as Local Binary Patterns (LBP) can be used. This method is more robust to variations in lighting and can handle images with lower resolution.

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA

lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

X = lfw_people.data
y = lfw_people.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

pca = PCA(n_components=100, whiten=True, random_state=0)
X_train_pca = pca.fit_transform(X_train)
X_test_pca = pca.transform(X_test)

clf = RandomForestClassifier()
clf.fit(X_train_pca, y_train)
y_pred = clf.predict(X_test_pca)

print(classification_report(y_test, y_pred))

Problem: Unbalanced Dataset

Another common problem with facial recognition systems is the issue of unbalanced datasets. This occurs when the dataset contains a disproportionate number of images of certain individuals or groups, leading to bias in the system. This can be particularly problematic in situations where the system is being used for security or surveillance, as it may lead to unequal treatment of different individuals or groups.

Solution:

One way to address this problem is to use techniques such as oversampling or undersampling to balance the dataset. For example, oversampling can be used to replicate examples in the minority class to balance the dataset. While Undersampling can be used to remove examples from the majority class to balance the dataset.

from sklearn.utils import resample

X = pd.concat([X_train, y_train], axis=1)

not_face = X[X.label==0]
face = X[X.label==1]

face_upsampled = resample(face, replace=True, n_samples=len(not_face), random_state=27)

upsampled = pd.concat([not_face, face_upsampled])

y_train = upsampled.label
X_train = upsampled.drop('label', axis=1)

Problem: Low-Resolution Images

Another problem with facial recognition systems is the issue of low-resolution images. This can occur when the images used to train the system or the images being processed by the system are of low quality.

Solution:

One way to address this problem is to use image enhancement techniques such as super-resolution to increase the resolution of the images. For example, you can use the package such as cv2 to resize the image to a higher resolution. Another technique that can be used is to use deep learning-based methods such as Generative Adversarial Networks (GANs) to generate high-resolution images from low-resolution images.

import cv2

def increase_resolution(image, scale_percent):
    width = int(image.shape[1] * scale_percent / 100)
    height = int(image.shape[0] * scale_percent / 100)
    dim = (width, height)
    return cv2.resize(image, dim, interpolation = cv2.INTER_LINEAR)

high_resolution_image = increase_resolution(low_resolution_image, 200)

or

from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model

def build_generator():
    model = Sequential()
    model.add(Dense(7*7*256, input_dim=100))
    model.add(Reshape((7, 7, 256)))
    model.add(UpSampling2D())
    model.add(Conv2D(128, kernel_size=3, padding="same"))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Activation("relu"))
    model.add(UpSampling2D())
    model.add(Conv2D(64, kernel_size=3, padding="same"))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Activation("relu"))
    model.add(Conv2D(3, kernel_size=3, padding="same"))
    model.add(Activation("tanh"))
    return model

The above solutions are widely used in the industry but there are other techniques that can be used to address low resolution images such as using larger training dataset or using deep learning techniques to extract features from low resolution images etc.

A brief introduction to Ageitgey face-recognition

Ageitgey face-recognition is a technology that uses computer algorithms to identify and match human faces. The process of face recognition involves several steps such as detection, alignment, feature extraction, and matching. The first step, detection, involves identifying the presence of a face in an image or video. This can be done using techniques such as Haar cascades, which are a type of classifier that uses a series of simple features to detect faces in images.

Once a face is detected, the next step is alignment. This involves aligning the face so that it is facing forward and in a consistent position. This is important for feature extraction, as it ensures that the same features are being extracted from each face. After alignment, feature extraction is performed. This involves extracting unique facial characteristics such as the shape and texture of the eyes, nose, and mouth. These features are then used to create a unique “face template” which can be used for matching. Finally, the matching step involves comparing the face template to a database of known faces to find a match. The matching can be done using techniques such as Euclidean distance, Cosine similarity, or Mahalanobis distance.

Most popular use cases for Ageitgey face-recognition

  1. Security and Surveillance: Ageitgey face-recognition can be used in security and surveillance systems to identify and track individuals in real-time. This technology can be integrated with CCTV cameras to automatically detect and identify individuals as they enter a building or area. The system can also be used to track individuals as they move through the area, and alert security personnel if an individual is behaving suspiciously.
import cv2
import face_recognition

# Load the video
video = cv2.VideoCapture("example.mp4")

# Load the known faces
known_faces = []
known_faces.append(face_recognition.load_image_file("person1.jpg"))
known_faces.append(face_recognition.load_image_file("person2.jpg"))

# Initialize variables
face_locations = []
face_encodings = []

while True:
    # Get the current frame
    ret, frame = video.read()

    # Exit the loop if the video has ended
    if not ret:
        break

    # Find the faces in the frame
    face_locations = face_recognition.face_locations(frame)
    face_encodings = face_recognition.face_encodings(frame, face_locations)

    # Loop through each face
    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        # Check if the face is a known face
        for known_face in known_faces:
            match = face_recognition.compare_faces([known_face], face_encoding)
            if match[0]:
                print("Known face detected")
                break
    # Display the frame
    cv2.imshow("Video", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture object
video.release()
  1. Biometric Authentication: Ageitgey face-recognition can be used as a biometric authentication method to grant access to devices, buildings, or sensitive information. This technology can be integrated with a security system to grant access to authorized individuals and deny access to unauthorized individuals. It can be used as an alternative to traditional authentication methods such as passwords or fingerprints.
  2. Personalized Services: Ageitgey face-recognition can be used to provide personalized services. For example, it can be used in retail stores to track customers’ preferences and make personalized recommendations. It can also be used in entertainment venues such as theme parks to offer personalized experiences based on a person’s preferences. This technology can also be used in healthcare to provide personalized medical treatment based on a patient’s unique facial characteristics.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • 18132 ошибка audi
  • 18118 ошибка фольксваген поло седан
  • 18118 ошибка vag
  • 18115 ошибка dsg 6
  • 18107 ошибка ауди

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии