why say empty function 'resize'? - python

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.

Related

Error using OpenCV for Connected Components on numpy arrays

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!

can't save the image after using PIL Image.thumbnail

I am quite confused cause when I try to save the resized version of an image it says 'AttributeError: 'NoneType' object has no attribute 'save''.
I looked over the internet and also to this question: Python Pillow's thumbnail method returning None but i already used the save function so i don't get why it doesn't work.
Here's my code:
from PIL import Image
imgg = Image.open('cropped.tif')
new_image = imgg.thumbnail((400, 400))
new_image.save('thumbnail_400.tif')
I bet it's something stupid but i can't see what it is. I appreciate any help.
thumbnail() is an extension method without a return object. The new_image variable will stay None in your case. You need to do this.
from PIL import Image
imgg = Image.open('cropped.tif')
imgg.thumbnail((400, 400))
imgg.save('thumbnail_400.tif')

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?

Categories

Resources