Error using OpenCV for Connected Components on numpy arrays - python

I'm trying to do a connected component analysis on an image using OpenCV in python. The images are in a '.czi' format so I am using aicsimageio to import the file into numpy array. However, I keep receiving the error:
OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\connectedcomponents.cpp:5632: error: (-215:Assertion failed) iDepth == CV_8U || iDepth == CV_8S in function 'cv::connectedComponents_sub1'
Below is some code similar to what I am trying to do. I will just create an numpy array for simplicity (instead of importing the image).
import numpy as np
import cv2
test = np.random.rand(512,512)
(T, thresh) = cv2.threshold(test, 0.5, 255, cv2.THRESH_BINARY)
num_labels, labels = cv2.connectedComponents(thresh)
This returns the error described above on the final line of code. The error seems to be something to do with the fact that the image wasn't imported using OpenCV, as I have got the same code to work when importing a random '.jpg' using OpenCV. I'm not sure why, since importing the '.jpg' using OpenCV returns a numpy array, i.e.:
image = cv2.imread(file)
type(thresh) == type(image)
returns True
Any help on how to fix this would be much appreciated!

Related

cv2.error: OpenCV(4.5.2) .error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

import cv2 #for image processing
import easygui #to open the filebox
import numpy as np #to store image
import imageio #to read image stored at particular path
import sys
import matplotlib.pyplot as plt
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
top=tk.Tk()
top.geometry('400x400')
top.title('Cartoonify Your Image !')
top.configure(background='white')
label=Label(top,background='#CDCDCD', font=('calibri',20,'bold'))
def upload():
ImagePath=easygui.fileopenbox()
cartoonify(ImagePath)
def cartoonify(ImagePath):
# read the image
originalmage = cv2.imread(ImagePath)
originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB)
#print(image) # image is stored in form of numbers
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-vi271kac\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Check the image address again. This usually happens when the image is not loaded correctly in any way. Try giving the address directly; something like "C:\\test.jpg"
import cv2
im = cv2.imread("WRONG IMAGE ADDRESS.jpg", 1)
im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
Update
You can also get the current folder path of your script and load your image from that.
Imagine your files structure are like this:
--RootProject
|-img.jpg
|-script.py
Then you can also do something like this:
script.py
import cv2
import sys
im = cv2.imread(sys.path[0]+"/img.jpg", 1)
im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
Try giving the image as a path, and one thing to be careful is about the slashes. Use \\ instead of \. Your path must look like D:\\file\\file1\\file2.
To check if it worker print type(cv2.imread(path)). If it prints <class 'numpy.ndarray'>, then you are good to go.
This may happen if your image file path is wrong, add your working folder then use as below:
image = cv2.imread('eye_face.jpg')
type(image)
then your image type will indicate as numpy.ndarray, if your image file path is wrong then the type will be NoneType.
This error is {wrong image location}. If suppose your image in another folder means use like this:
img=cv2.imread("../images/car.jpg",1)
This seems to be the path issue in windows. I changed it to a full path like this and it worked.
filename = "D:\Sandbox\Github\opencv-project\Resources\Photos\cats.jpg"
I was trying to read images from a folder and having the same trouble. I had a non-image in one of the folders that was the problem.
I solved the same problem by adding:
data = cv2.imread('path_to_your_image', as_grey =True)
and then try to also add the flags = cv2.DFT_COMPLEX_OUTPUT to this line
dft = cv2.dft(np.float32('your_image'),flags = cv2.DFT_COMPLEX_OUTPUT)
there are many solutions for this issue out there.
This might be because of your camera issue or the camera driver issue. If you are using any USB camera then cross-check its connection and ensure that no other programs are using the same camera.
If your camera is working then you might put the wrong image path. Verify the image path. Also, try to put a hardcoded path like C:\\image1.png if needed.
import cv2
im = cv2.imread("C:\\image1.png", 1)
im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
Please check the extension you give to the path. JPEG,PNG or anything else.
Check if your camera has been disabled in the device manager, or else upadate it.

Warp an image from given coordinates - OpenCV Python

Im learning OpenCV at the moment. The goal of this exercise is to take the 4 corner points of a Pokercard from a laying perspective and warping it flat in front of you.
As you can see I have the coordinates mapped out in pts1/ corners assigned correctly (It seems like that at least, after checking).
After outputting imgWarped it throws the error:
traceback (most recent call last):
File "C:\Users\draco\PycharmProjects\Reader\main.py", line 101, in <module>
imgWarped = cv2.warpPerspective(img,matrix,(width,height))
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\imgproc\src\imgwarp.cpp:3143: error: (-215:Assertion failed) _src.total() > 0 in function 'cv::warpPerspective'
The documentations online did not help me much resolving this problem. What does my error message actually mean and how does it happen? Is there a better practice?
Here is the code:
import cv2
import numpy as np
img = cv2.imread("Resources/cards.jpg")
width,height = 250,350
pts1 = np.float32([[124,161],[189,155],[200,231],[135,245]])
pts2 = np.float32([[0,0],[width,0],[width,height],[0,height]])
matrix = cv2.getPerspectiveTransform(pts1,pts2)
---Here is the error --> imgWarped = cv2.warpPerspective(img,matrix,(width,height))
cv2.imshow("Warped Img", imgWarped)
cv2.waitKey(0)
I have used your code with my own image to regenerate the error, but it worked fine.
You can either post to us your input image, or make sure the point you select is not larger than your image it self, coz I can see that you are hard coding the points

opencv read image assertion failed

I am a newbie to python and opencv.
trying to read image.
here is my code :-
import cv2
import numpy
img = cv2.imread('Test1.jpg',0)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
here is the error generated :-
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /opt/concourse/worker/volumes/live/68762549-a7cd-401a-4fc4-6547354af396/volume/opencv_1512680491081/work/modules/highgui/src/window.cpp,
line 331 Traceback (most recent call last): File
"/Users/vinayak/PycharmProjects/Python_test1/test_img.py", line 4, in
cv2.imshow('image',img) cv2.error: /opt/concourse/worker/volumes/live/68762549-a7cd-401a-4fc4-6547354af396/volume/opencv_1512680491081/work/modules/highgui/src/window.cpp:331:
error: (-215) size.width>0 && size.height>0 in function imshow
please help me identify the fault. thanks in advance !
This error means you didnĀ“t loaded the image and img is empty.
There is a known error in imread for cv2. You can try replacing the imread call with this portion :
import matplotlib.pyplot as plt
img = plt.imread('Test1.jpg')
matplotlib does not have the same error on cv2.
The code is correct, this is the right way to load and display an image unsing OpenCV in Python, the additional argument you passed (0) means you're loading the image as grayscale and is the numeric value for the enum cv.IMREAD_GRAYSCALE
opencv load image tutorial
link to enums
Just for the sake of completeness, here the basic code I tested
import cv2 as cv
img = cv.imread('C:\\path\\to\\my\\Image\\image.bmp',0)
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()
Due to this, the issue is most probably related to the path your're passing to cv.imread function
Are you sure your image is in the same working directoy you're
using?(and I bet is not...)
Did you try to change the relative path you gave with a complete absolute
path?

Run into this error while using Pillow

I am using Pillow (4.3.0) to perform image quantization. When I run the image quantization function in PIL, I get this error saying ValueError: dependency required by this method was not enabled at compile time
Here is a MWE of my code
from PIL import Image
import numpy as np
I = Image.open('test.jpeg')
Q = Image.Image.quantize(I, colors = 64,method = 3, kmeans = 0, palette = None)
I is an RGB image (32x32x3). I am using Elementary OS. How do I sort this error out?

Why can't I create an image and set it as the background in OpenCV?

So, this is what I am trying:
import cv2
import cv2.cv as cv
cv2.namedWindow(threeDWinName, cv2.CV_WINDOW_AUTOSIZE)
img2 = cv.CreateImage((320, 240), 32, 1)
cv2.imshow(threeDWinName,img2)
Does anybody know what is going wrong with this? I get TypeError: <unknown> is not a numpy array
Thanks
The more recent version of OpenCV, cv2 uses numpy arrays for images, the preceding version cv used opencv's special Mat's. In your code you've created an image as a Mat using the old cv function CreateImage, and then tried to view it using the newer cv2.imshow function, but cv2.imshow expects a numpy array...
...so all you need to do is import numpy, and then change you CreateImage line to:
img2 = np.zeros((320,240),np.float32)
And then it should be fine :)

Categories

Resources