opencv2 python3 imread with NoneType - python-3.x

I program in Ubuntu system with python3, opencv2. There are several images in the folder that need to be processed. When I use imread, print(img.shape) shows AttributeError: 'NoneType' object has no attribute 'shape'. And I checked the created images' size is 0 bytes. The strange thing is that there are some images can be read successfully, but some are NoneType. Thanks for your help.
import glob as gb
import cv2
import random
import os
import numpy as np
shared_path="/home/train_1/"
folder_list=["HTC-1-M7"]
for j in range(len(folder_list)):
output_path=os.path.join("/home/test/",folder_list[j])
camera_path= os.path.join(shared_path,folder_list[j])
img_path = gb.glob(camera_path+"/*.jpg")
counter=1
for path in img_path:
img = cv2.imread(path)
print(img.shape)
kernel = np.array([[-1,2,-2,2,-1],[2,-6,8,-6,2],[-2,8,-12,8,-2],[2,-6,8,-6,2],[-1,2,-2,2,-1]],np.float32)/12
img = cv2.filter2D(img,-1,kernel)

It means that somewhere a function which should return a image just returned None and therefore it has no shape attribute.
Try print(img) to check if your image is None or an actual numpy object. You probably get this error because your image path may be wrong in a way. Make sure your path is completely correct.

Related

Argument error when compiling .exe from Python using PyInstaller

I am trying to write a screen recorder program in python. My code runs normally in the compiler. But when I convert it to .exe, it raises this error:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): project.avi in function 'cv::icvExtractPattern'
I used pyinstaller to convert to .exe.
This is my code:
from tkinter import*
from tkinter import messagebox as msj
from PIL import ImageTk, Image
from PIL import ImageGrab
import os
import time
import cv2
import numpy as np
import glob
recording=False
i = 0
size = 100, 100
mainWindow=Tk()
mainWindow.title("ScreenRecorder")
mainWindow.geometry("200x200")
scriptDirectory = (os.path.dirname(os.path.realpath(__file__)))
def convert(imageCount):
img_array = []
for ip in range(1,imageCount):
x="snap"+str(ip)+".jpg"
for filename in glob.glob(x):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 9, size)
for iz in range(len(img_array)):
out.write(img_array[iz])
out.release()
for a in range(1,imageCount+1):
os.remove("snap"+str(a)+".jpg")
def record():
global i
print(recording)
if(recording==True):
i+=1
fileName= ("snap"+str(i))
#time.sleep(0.00005)
image = ImageGrab.grab()
name=fileName+".jpg"
image.save(name,'JPEG')
imgX = (Image.open("snap"+str(i)+".jpg"))
imgX= imgX.resize(size, Image.ANTIALIAS)
imgX=ImageTk.PhotoImage(imgX)
mainWindow.after(1, record)
def startButton():
global recording
print("ehe")
recording=True
record()
def stopButton():
global recording
recording=False
record()
convert(i)
startButton=Button(text="Start",command=startButton)
startButton.pack()
stopButton=Button(text="Stop",command=stopButton)
stopButton.pack()
mainWindow.after(1, record)
mainWindow.mainloop()
I can just advise you to use another method, i think it's more simple, try to use 'auto py to exe'.This is a module that can be installed from the net or from the pip installer.
see from here.This the only way that i use for my codes.
Secondly, iknow that if the program is not opened using the format of .py will never be opened at .exe
hope i helped you.

Error Opening PGM file with PIL and SKIMAGE

I have following Image file:
Image
I used PIL and Skimage to open it but I get following errors
First with PIL (tried with and without trucate option):
Code:
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
img = Image.open("image_output.pgm")
Erorr:
OSError: cannot identify image file 'image_output.pgm'
And with Skimage:
Code:
from skimage import io
img = io.imread("image_output.pgm")
Error:
OSError: cannot identify image file <_io.BufferedReader name='image_output.pgm'>
I can open the file with GUI applications like system photo viewer and Matlab.
How can I diagnose what is wrong with image? I compared the byte data with other PGM files which I can open in Python, but could not identify the difference.
Thanks.
Your file is P2 type PGM, which means it is in ASCII - you can view it in a normal text editor. It seems neither PIL, nor skimage want to read that, but are happy to read the corresponding P5 type which is identical except it is written in binary, rather than ASCII.
There are a few options...
1) You could use OpenCV to read it:
import cv2
im = cv2.imread('a.pgm')
2) You could convert it to P5 with ImageMagick and then read the output.pgm file with skimage or PIL:
magick input.pgm output.pgm
3) If adding OpenCV, or ImageMagick as a dependency is a real pain for you, it is possible to read a PGM image yourself:
#!/usr/bin/env python3
import re
import numpy as np
# Open image file, slurp the lot
with open('input.pgm') as f:
s = f.read()
# Find anything that looks like numbers
# Technically, there could be comments that should be ignored
l=re.findall(r'[0-9P]+',s)
# List "l" will contain: P5, width, height, 255, pixel1, pixel2, pixel3...
# Technically, if l[3]>255, you should change the type of the Numpy array to uint16, but that is not the case
w, h = int(l[1]), int(l[2])
# Make Numpy image from data
ni = np.array(l[4:],dtype=np.uint8).reshape((h,w))

Google Colab - AttributeError: 'numpy.ndarray' object has no attribute 'seek' and 'read'

I'm trying to concatenate 3 images horizontaly. I've found a way that seems good enough on the the internet, the problem is that I'm having two errors that I can't figure out how to fix.
Note: I'm using Google Colab with Python 3.
Here is the errors:
AttributeError: 'numpy.ndarray' object has no attribute 'seek'
AttributeError: 'numpy.ndarray' object has no attribute 'read'
My code:
import matplotlib.pyplot as plt
import numpy as np
import sys
import PIL
import cv2
rgb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_1_3.tif")
tir = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_TIR_1_3.tif")
qb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_QB_1_3.tif")
list_im = [rgb, tir, qb]
imgs = [ PIL.Image.open(i) for i in list_im ]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
# save that beautiful picture
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'Trifecta.jpg' )
Apparently the error happens on this line: ---> 12| imgs = [ PIL.Image.open(i) for i in list_im ]
And because of it I tried to update the Pillow library to 5.3.0, but the error still happens, what should I do?
How about not using pil, seems like opencv can do want you want
import matplotlib.pyplot as plt
import numpy as np
import sys
import cv2
rgb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_1_3.tif")
tir = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_TIR_1_3.tif")
qb = cv2.imread("/content/teste/LC08_L1TP_222063_20180702_20180716_01_T1_QB_1_3.tif")
list_im = [rgb, tir, qb]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_width = min([img.shape[1] for img in list_im])
min_height = min([img.shape[0] for img in list_im])
list_img = [cv2.resize(img, (min_width, min_height)) for img in list_im]
imgs_comb = np.hstack( list_img )
# save that beautiful picture
cv2.imwrite('result.jpg', imgs_comb)

Read a .jpg from RAM

from io import StringIO
from PIL import Image
import requests
response = requests.get(image.url)
# Works fine, but requests a disk write.
f = open('tmp.jpg', 'bw')
f.write(response.content)
img = Image.open('tmp.jpg')
# Fails with `OSError: cannot identify image file <_io.StringIO object at 0x7fb666238a68>`
#file = StringIO(str(response.content))
#img = Image.open(file)
I am trying to run the code from this tutorial but in python3. The commented out version is the closest I have gone to the original idea of "get an image from the network into RAM and work with that". I don't mind using cv2 if easier. How do I write this code pythonically and efficiently?
As Mark Setchell said, you likely want BytesIO not StringIO.
from io import BytesIO
from PIL import Image
import requests
response = requests.get(image.url)
file = BytesIO(response.content)
img = Image.open(file)

python cv2.imread return none on 6th image

I am trying to import and read all images in a folder. However, when I have more than 5 images, cv2.imread returns none for the 6th image. I have tried using different file names, different files, etc, but I can't get it to work.
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tkinter import filedialog
import os
from mpl_toolkits.mplot3d import Axes3D
global scan_dir
scan_dir = filedialog.askdirectory()
print(scan_dir)
x=os.listdir(scan_dir)
img={}
print(x)
for i in range(0,len(x)):
print(i)
img[i] = cv2.imread(x[i], cv2.IMREAD_GRAYSCALE)
indices[i] = np.where(img[i]<100)
I get the following error...(None is the return of print(img[i] on 6th iteration of the loop)
None
Traceback (most recent call last):
File "C:\CodeRepository\US-3D\GettingCloser.py", line 55, in <module>
indices[i] = np.where(img[i]<100)
TypeError: '<' not supported between instances of 'NoneType' and 'int'
I have the same problem if I try this
global scan_dir
scan_dir = filedialog.askdirectory()
print(scan_dir)
x=os.listdir(scan_dir)
img = cv2.imread(x[5], cv2.IMREAD_GRAYSCALE)
It will return that img is None. This is true for anything beyond the 5th image.
Must be something wrong with the file. dicts are an unordered Data structure. Should not give error always on 5th iteration. However, I have made the changes which will not throw the error. But you need to debug that image
for i in range(0,len(x)):
print(i)
img[i] = cv2.imread(x[i], cv2.IMREAD_GRAYSCALE)
if img[i]:
indices[i] = np.where(img[i]<100)

Resources