AttributeError: 'Tensor' object has no attribute 'to_sparse' - python

I was trying out this tutorial using this Plant Leaves dataset (with over 35k images consisting .JPG, .PNG as well as .JPEG files) with tensorflow version 1.14
And I followed similar steps except; skipping "Load using keras.preprocessing" part. I directly jumped over to "Load using tf.data" part. But when I ran the snippet it threw me this error:
File "D:\Softwares\Anaconda\lib\site-packages\tensorflow\python\ops\ragged\ragged_string_ops.py", line 640, in strings_split_v1
return ragged_result.to_sparse()
AttributeError: 'Tensor' object has no attribute 'to_sparse'
Complete error:
My code snippet is:
dir_root=pathlib.Path("D:/Projects/IIIT/LeafID/Dataset/PlantVillage")
list_ds=tf.data.Dataset.list_files(str(dir_root/"*/*"))
def getLabel(fpath):
parts = tf.strings.split(fpath, os.path.sep)
return parts[-2] == clnames
def decodeimg(img):
img=tf.image.decode_jpeg(img,channels=3)
img=tf.image.convert_image_dtype(img,tf.float32)
return tf.image.resize(img,[64,64])
def process_path(fpath):
label=getLabel(fpath)
img=tf.io.read_file(fpath)
img=decodeimg(img)
return img, label
label_ds=list_ds.map(process_path,num_parallel_calls=AUTOTUNE)
which is almost similar to the code here, except the variables.
I couldn't understand what's the problem here?
Is there something wrong with the process of images getting converted to tensor? Because when I open ragged_string_ops.py, it shows me something like this:
if result_type == "SparseTensor":
return ragged_result.to_sparse()
T.I.A.

I ran into a similar issue working through that tutorial, and found this issue suggesting it's a bug with strings.split in certain tensorflow versions (I saw this issue in tf 1.14, and the OP in the github issue saw it in 1.15): https://github.com/tensorflow/tensorflow/issues/33623
From the linked issue comments, it looks like two possible solutions are
(1) adding brackets around your string, e.g. c = tf.strings.split(['a b'])
or
(2) adding resultType='RaggedTensor', e.g. tf.strings.split('a b',result_type='RaggedTensor') to return a tensor (although this looks like it's buggy behavior, and may be corrected in later versions of tf).
Hope this helps.

Related

'str' object has no attribute 'call' when converting .model to tflite file

I have been following this tutorial to perform voice command recognition for a couple words on my ESP32: https://github.com/atomic14/voice-controlled-robot
I was able to train my model and have the "fully_trained.model" file: "fully_trained.model"
Currently I am trying to convert the .model file into the tflite file, however I am getting the "'str' has no attribute 'call'" error: Code, Code, Errors
My tensorflow version is 2.6.2 and python version is 3.10.
Unfortunately, I do not have 10 reputation points yet, so I couldnt embed the images.
If you use tf.lite.TFLiteConverter.from_keras_model you need to pass the tf.keras.Model instance, not the path to the saved_model folder.
Use tf.lite.TFLiteConverter.from_saved_model() instead and pass the path to the "fully_trained.model" folder.
You've passed "fully_trained.model", with quotation marks, as an argument to TFLiteConverter. That's a string. Give the model a name and pass that name as an argument to the converter, without quotation marks.

Is there any problem with the OpenSlide.read_region function?

I am using the python API of openslide packages to read some ndpi file.When I use the read_region function, sometimes it return a odd image. What problems could have happend?
I have tried to read the full image, and it will be worked well. Therefore, I think there is no problem with the original file.
from openslide import OpenSlide
import cv2
import numpy as np
slide = OpenSlide('/Users/xiaoying/django/ndpi-rest-api/slide/read/21814102D-PAS - 2018-05-28 17.18.24.ndpi')
image = slide.read_region((1, 0),6, (780, 960))
image.save('image1.png')
The output is strange output
As the read_region documentation says, the x and y parameters are always in the coordinate space of level 0. For the behavior you want, you'll need to multiply those parameters by the downsample of the level you're reading.
This appears to be a version-realted bug, see also
https://github.com/openslide/openslide/issues/291#issuecomment-722935212
The problem seems to relate to libpixman verions 0.38.x . There is a Workaround section written by GunnarFarneback suggesting to load a different version first e.g.
export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpixman-1.so.0.34.0
upadte easier solution is:
We are using Python 3.6.8+ and this did the trick for us: conda install pixman=0.36.0

When I save the output of displacy.render(doc, style="dep") to a svg file, there is a TypeError: write() argument must be str, not None

I want to save the visualisation of spaCy with the code that spaCy offers here : https://spacy.io/usage/visualizers
Here is my code :
nlp = spacy.load("en_core_web_sm")
doc = nlp(u"Autonomous cars shift insurance liability toward manufacturers")
svg = spacy.displacy.render(doc, style="dep")
output_path = Path(os.path.join("./", "sentence.svg"))
output_path.open('w', encoding="utf-8").write(svg)
But when I execute this code, there is an error : TypeError: write() argument must be str, not None
So how can I save the output of spacy.displacy.render ? How can I fix this error ?
The code provided in the question works fine, when executed in an IDE like PyCharm.
However, displacy.render() works slightly differently in a Jupyter notebook, cf the documentation here and here:
If you’re running a Jupyter notebook, displaCy will detect this and return the markup in a format ready to be rendered and exported.
You can overwrite this automated detection by explicitly setting jupyter=False in the render() call.

NoneType error while region of interest

for i in range(0,3):
for j in range(0,3):
im=img[100*i:(100*i)+100,100*j:(100*j)+100]
shape= shapedetect(im)
clr= colordetect(im)
size_s= size(im)
list.append(shape)
list_clr.append(clr)
list_siz.append(size_s)
list_contnr.append(check_cnb(shape,clr,size_s))
This is part of my program in opencv python. I have taken the region of interest
of and image which is already declared earlier i.e. img=cv2.imread('board_8.jpg')
but while running the code it gives me an error NoneType has no attribute '_getitem_' on the line:
im=img[100*i:(100*i)+100,100*j:(100*j)+100]
This error occurs if the image img has not been properly read in. Most likely this is due to the fact that the path to the image is wrong and there is no file named 'board_8.jpg' in the current working directory.

OpenCV Python not opening images with imread()

I'm not entirely sure why this is happening but I am in the process of making a program and I am having tons of issues trying to get opencv to open images using imread. I keep getting errors saying that the image is 0px wide by 0px high. This isn't making much sense to me so I searched around on here and I'm not getting any answers from SO either.
I have taken about 20 pictures and they are all using the same device. Probably 8 of them actually open and work correctly, the rest don't. They aren't corrupted either because they open in other programs. I have triple checked the paths and they are using full paths.
Is anyone else having issues like this? All of my files are .jpgs and I am not seeing any problems on my end. Is this a bug or am I doing something wrong?
Here is a snippet of the code that I am using that is reproducing the error on my end.
imgloc = "F:\Kyle\Desktop\Coinjar\Test images\ten.png"
img = cv2.imread(imgloc)
cv2.imshow('img',img)
When I change the file I just adjust the name of the file itself the entire path doesn't change it just refuses to accept some of my images which are essentially the same ones.
I am getting this error from a later part of the code where I try to use img.shape
Traceback (most recent call last):
File "F:\Kyle\Desktop\Coinjar\CoinJar Test2.py", line 14, in <module>
height, width, depth = img.shape
AttributeError: 'NoneType' object has no attribute 'shape'
and I am getting this error when I try to show a window from the code snippet above.
Traceback (most recent call last):
File "F:\Kyle\Desktop\Coinjar\CoinJar Test2.py", line 11, in <module>
cv2.imshow('img',img)
error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow
Probably you have problem with special meaning of \ in text - like \t or \n
Use \\ in place of \
imgloc = "F:\\Kyle\\Desktop\\Coinjar\\Test images\\ten.png"
or use prefix r'' (and it will treat it as raw text without special codes)
imgloc = r"F:\Kyle\Desktop\Coinjar\Test images\ten.png"
EDIT:
Some modules accept even / like in Linux path
imgloc = "F:/Kyle/Desktop/Coinjar/Test images/ten.png"
From my experience, file paths that are too long (OS dependent) can also cause cv2.imread() to fail.
Also, when it does fail, it often fails silently, so it is hard to even realize that it failed, and usually something further the the code will be what sparks the error.
Hope this helps.
Faced the same problem on Windows: cv.imread returned None when reading jpg files from a subfolder. The same code and folder structure worked on Linux.
Found out that cv.imread processes the same jpg files, if they are in the same folder as the python file.
My workaround:
copy the image file to the python file folder
use this file in cv.imread
remove redundant image file
import os
import shutil
import cv2 as cv
image_dir = os.path.join('path', 'to', 'image')
image_filename = 'image.jpg'
full_image_path = os.path.join(image_dir, image_filename)
image = cv.imread(full_image_path)
if image is None:
shutil.copy(full_image_path, image_filename)
image = cv.imread(image_filename)
os.remove(image_filename)
...
I had i lot of trouble with cv.imread() not finding my Image. I think i tryed everything involving changing the path. The os.path.exists(file_path) function also gave me back a True.
I finaly solved the problem by loading the images with imageio.
img = imageio.imread('file_path')
This also loads the img in a numpy array and you can use funktions like cv.matchTemplate() on this object. But i would recomment if u are doing stuff with multiple images that you then read all of them with imageio because i found diffrences in the arrays produced by .imread() from the two libs (opencv, imageio) on a File both of them could open.
I hope i could help someone
Take care to :
try imread() with a reliable picture,
and the correct path in your context like (see Kyle772 answer). For me either //or \.
I lost a couple of hours trying with 2 images saved from a left click in a browser. As soon as I took a personal camera image, it works fine.
Spyder screen shot
#context windows10 / anaconda / python 3.2.0
import cv2
print(cv2.__version__) # 3.2.0
imgloc = "D:/violettes/Software/Central/test.jpg" #this path works fine.
# imgloc = "D:\\violettes\\Software\\Central\\test.jpg" this path works fine also.
#imgloc = "D:\violettes\Software\Central\test.jpg" #this path fails.
img = cv2.imread(imgloc)
height, width, channels = img.shape
print (height, width, channels)
python opencv image-loading imread
I know that the question is already answered but in case anybody still is not able to load images with imread. It may be because there are letters in the string path witch imread does not accept.
For exmaple umlauts and diacritical marks.
My suggestion for everyone facing the same problem is to try this:
cv2.imshow("image", img)
The img is keyword. Never forget.
When you get error like this AttributeError: 'NoneType' object has no attribute 'shape'
Try with new_image=image.copy

Categories

Resources