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?
Related
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!
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.
the error that i get is .
error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/resize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'resize'
fname_images = np.array(df_skin['image_id'])
file_to_read =('/content/drive/MyDrive/DATASET/HAM10000_images_part_1')+str(fname_images[0])+'.jpg'
import cv2
from cv2 import imread
from cv2 import resize
img = imread(file_to_read)
img2 = resize(img,(100,100))
# show one exampe image
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.imshow(img[:,:,::-1])
plt.title('Original image')
plt.subplot(1,2,2)
plt.imshow(img2[:,:,::-1])
plt.title('Resized image for DenseNet')
plt.show()
imread() won't throw an exception if it can't find the image file -- it just returns None. The error occurs when you try to pass this to resize().
I think the pathname to the image file is wrong -- is HAM10000_images_part_1 a directory? If so, you forgot to add a slash after, and so the code tries to read an image named something like HAM10000_images_part_1bicycle.jpg which of course does not exist.
Try using Pillow and doing the .resize((x, y)) on it. And also check the path to make sure everything is good.
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
In this code we are preprocessing an RGB image for Tesseract OCR using tools such as cv2, NumPy and PIL. When this code is executed in the Python 2.7.13 Shell, I recieve the following error message.
Traceback (most recent call last): File "C:\Automation\OCR\images\OCR_Preprocessing_ RGB.py", line 23, in <module> cv2.THRESH_BINARY,11,2) error: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\thresh.cpp:1446: error: (-215) src.type() == CV_8UC1 in function cv::adaptiveThreshold
Here is the code that error generated from. I have marked lines of code where I think the problem may be.
import cv2
import numpy as np
from matplotlib import pyplot as plt
from cycler import cycler
from PIL import Image, ImageEnhance
# Loads the image then enhances it
image = Image.open('teleCapture.png')
contrast = ImageEnhance.Contrast(image)
img = contrast.enhance(2)
img = np.asarray(img)
r,g,b,a = cv2.split(img) // I know the issue is here, I have too many channels for an RGB image or I am merginf them wrong.
contrast = cv2.merge([b,g,r]) //"Contrast" was used as a src during Thresholding, is this what it should be?
# Adaptive Gaussian Thresholding //The problem may be within the thresholding, does this thresholding function only work using grayscale images?
th1 = cv2.adaptiveThreshold(contrast,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
# Otsu's thresholding
ret2,th2 = cv2.threshold(contrast,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(contrast,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# writes enhanced and thresholded img
cv2.imwrite('preprocessedTeleCapture.png', th2)
Threshold method need 1 channel image as input, and you give 3 channel, that's the problem shown in error message.