I'm trying to convert a .npy image to a nii.gz image, I'm having various problems even though I'm following instructions correctly.
This is the code I'm using:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
print(img_array1.shape)
print(img_array1.dtype)
normal_array = "D:/teste volumes slicer/teste01.npy"
print ("done")
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
About the image: (332, 360, 360) float64 (this is what we got when we print the shape and dtype)
https://ibb.co/mRyTrw7 - image that shows the error and the image's information
The error message:
Traceback (most recent call last):
File "d:\teste volumes slicer\conversor.py", line 16, in <module>
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1756, in __init__
super(Nifti1Pair, self).__init__(dataobj,
File "C:\Python39\lib\site-packages\nibabel\analyze.py", line 918, in __init__
super(AnalyzeImage, self).__init__(
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 469, in __init__
self.update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 2032, in update_header
super(Nifti1Image, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1795, in update_header
super(Nifti1Pair, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 491, in update_header
shape = self._dataobj.shape
AttributeError: 'str' object has no attribute 'shape'
The problem with your code is instead of passing your Numpy-array (your image), you are passing the path of the image to the Nifti1Image function.
This is the correct way to convert it:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))
Related
I keep getting the below error when I try to access my model on hugging face spaces. I am building my model in a Kaggle notebook, then downloading to a pkl file to my spaces repo and git pushing to HF spaces. Below is my ImageDataLoaders class that I am using, as I suspect the error is coming from here.
dls = ImageDataLoaders.from_folder(path, valid_pct = 0.2, item_tfms=Resize(460), batch_tfms=aug_transforms(size=224, min_scale=0.75))
Here is the error I am getting.
Traceback (most recent call last):
File "app.py", line 5, in <module>
learn = load_learner('new_model.pkl')
File "/home/user/.local/lib/python3.8/site-packages/fastai/learner.py", line 428, in load_learner
try: res = torch.load(fname, map_location=map_loc, pickle_module=pickle_module)
File "/home/user/.local/lib/python3.8/site-packages/torch/serialization.py", line 712, in load
return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args)
File "/home/user/.local/lib/python3.8/site-packages/torch/serialization.py", line 1049, in _load
result = unpickler.load()
File "/home/user/.local/lib/python3.8/site-packages/torch/serialization.py", line 1042, in find_class
return super().find_class(mod_name, name)
AttributeError: Custom classes or functions exported with your `Learner` not available in namespace.\Re-declare/import before loading:
Can't get attribute 'Resampling' on <module 'PIL.Image' from '/home/user/.local/lib/python3.8/site-packages/PIL/Image.py'>
Here is my fill app.py code.
from fastai.vision.all import *
import gradio as gr
import skimage
learn = load_learner('new_model.pkl')
categories = ('deer', 'elk', 'moose')
def classify_image(img):
img = PILImage.create(img)
pred, idx, probs = learn.predict(img)
return dict(zip(categories, map(float,probs)))
image = gr.inputs.Image(type='pil', shape=(192,192))
label = gr.outputs.Label()
intf = gr.Interface(fn=classify_image, inputs=image, outputs=label)
intf.launch(inline=False)
I am trying to make a map in python using shapefiles I have downloaded from bbike.org. Here is my code:
import geopandas as gpd
import os
import sys
import matplotlib.pyplot as plt
bos_files_list = ['buildings.shx', 'landuse.shx', 'natural.shx', 'places.shx', 'points.shx', 'railways.shx', 'roads.shx']
cur_path = os.path.dirname(__file__)
def maps_of_bos(files):
for x in range(len(files)):
os.chdir(f'location/of/file')
f = open(f'{files[x]}', 'r')
gpd.read_file(f)
z = maps_of_bos(bos_files_list)
z.plot()
plt.show()
However, my error output is as follows:
Traceback (most recent call last):
File "test.py", line 16, in <module>
z = maps_of_bos(bos_files_list)
File "test.py", line 13, in maps_of_bos
gpd.read_file(f)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/geopandas/io/f
ile.py", line 76, in read_file
with reader(path_or_bytes, **kwargs) as features:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in
__enter__
return next(self.gen)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/__init__
.py", line 206, in fp_reader
dataset = memfile.open()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/io.py",
line 63, in open
return Collection(vsi_path, 'w', crs=crs, driver=driver,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/fiona/collecti
on.py", line 126, in __init__
raise DriverError("no driver")
fiona.errors.DriverError: no driver
I am relatively new to python, and don't really understand my error. can someone please help me?
According to the docs read_file should take the path to the file not an object.
gpd.read_file(f'{files[x]}')
you dont need
f = open(f'{files[x]}', 'r')
So I am trying to create a Python Program to detect similar details in two images using Python's OpenCV. I have the two images and they are in my current directory, and they exist (see the code in lines 6-17). But I am getting the following error when I try running it.
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
path1 = "WIN_20171207_13_51_33_Pro.jpg"
path2 = "WIN_20171207_13_51_43_Pro.jpg"
if os.path.isfile(path1):
img1 = cv2.imread('WIN_20171207_13_51_33_Pro.jpeg',0)
else:
print ("The file " + path1 + " does not exist.")
if os.path.isfile(path2):
img2 = cv2.imread('WIN_20171207_13_51_43_Pro.jpeg',0)
else:
print ("The file " + path2 + " does not exist.")
orb = cv2.ORB_create()
kpl1, des1 = orb.detectAndCompute(img1,None)
kpl2, des2 = orb.detectAndCompute(img2,None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x:x.distance)
img3 = cv2.drawMatches(img1,kpl1,img2,kpl2,matches[:10],None, flags=2)
plt.imshow (img3)
plt.show()
Here is the error I keep on getting...
Traceback (most recent call last):
File "C:\Users\jweir\source\repos\BruteForceFeatureDetection\BruteForceFeatureDetection\BruteForceFeatureDetection.py", line 31, in <module>
plt.imshow (img3)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in imshow
**kwargs)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
return func(ax, *args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshow
im.set_data(X)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\image.py", line 600, in set_data
raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float
Can someone please explpain to me why I am getting this error, what it means, and how to fix it.
You're not actually reading in an image.
Check out what happens if you try to display None in matplotlib:
plt.imshow(None)
Traceback (most recent call last):
File ".../example.py", line 16, in <module>
plt.imshow(None)
File ".../matplotlib/pyplot.py", line 3157, in imshow
**kwargs)
File ".../matplotlib/__init__.py", line 1898, in inner
return func(ax, *args, **kwargs)
File ".../matplotlib/axes/_axes.py", line 5124, in imshow
im.set_data(X)
File ".../matplotlib/image.py", line 596, in set_data
raise TypeError("Image data can not convert to float")
TypeError: Image data can not convert to float
You're reading WIN_20171207_13_51_33_Pro.jpeg but you're checking if WIN_20171207_13_51_33_Pro.jpg exists. Note the different extensions. Why do you have the filename written twice (and differently)? Just simply write:
if os.path.isfile(path1):
img1 = cv2.imread(path1, 0)
else:
print ("The file " + path1 + " does not exist.")
Note that even if you put a bogus file into cv2.imread(), the resulting image will just be None, which doesn't error in any of the subsequent function calls until matplotlib tries to draw it. If you print(img1) after reading, you'll see it's None and not reading properly.
I do not know whether it is relevant with your case but since we assigning the file path in string type like cv2.imread("filepathHere"), if arguments like "\b" or "\r" occurs in the file path it causes program to pop an error such as this.
When I encountered such an error before, I changed the file name from file / brick.png to ibrick.png and the problem was resolved.
I am trying to display an image in python and I am not 100% sure why imshow() is throwing an error.
The error trace is :
Traceback (most recent call last):
File "knn.py", line 65, in <module>
digit_axes.imshow(paths[0],cmap = cm.Greys_r)
File "/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py", line 1892, in inner
return func(ax, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 5118, in imshow
im.set_data(X)
File "/usr/local/lib/python2.7/site-packages/matplotlib/image.py", line 545, in set_data
raise TypeError("Image data can not convert to float")
TypeError: Image data can not convert to float
The code is as follows:
paths = []
paths.append('./images/image1.png')
digit_axes = main_figure.add_subplot(211)
digit_axes.get_xaxis().set_visible(False)
digit_axes.get_yaxis().set_visible(False)
digit_axes.set_title('Image')
digit_axes.imshow(paths[0],cmap = cm.Greys_r)
I think I found the solution by using imread()
img = imread(paths[0])
digit_axes.imshow(img,cmap = cm.Greys_r)
I'm working in python with many images.
While I'm analyzing this
when I use:
from skimage import color
from skimage import io
img = color.rgb2gray(io.imread(path))
I get this error:
Traceback (most recent call last):
File "C:\wamp\www\NewIESP\FUNZIONApy\up1feature.py", line 180, in <module>
updatefeatures(infile)
File "C:\wamp\www\NewIESP\FUNZIONApy\up1feature.py", line 43, in updatefeatures
temp = compareup1features.comparison(path)
File "C:\wamp\www\NewIESP\FUNZIONApy\compareup1features.py", line 496, in comparison
skellist = moduloSkeleton.skelfeatures(path1img)
File "C:\wamp\www\NewIESP\FUNZIONApy\moduloSkeleton.py", line 1418, in skelfeatures
img = color.rgb2gray(io.imread(path))
File "C:\Python27\Lib\site-packages\skimage\color\colorconv.py", line 661, in rgb2gray
return _convert(gray_from_rgb, rgb[:, :, :3])[..., 0]
File "C:\Python27\Lib\site-packages\skimage\color\colorconv.py", line 462, in _convert
return np.ascontiguousarray(out)
File "C:\Python27\Lib\site-packages\numpy\core\numeric.py", line 409, in ascontiguousarray
return array(a, dtype, copy=False, order='C', ndmin=1)
MemoryError
How can I solve this memory error?
If it is not possible, how can I say to "recognize" this kind of image and skip it!?