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)
Related
What should I do? I'm getting this error. I want add some tags for FLAC.
I searched but i didnt find anythings. Please help me.
Traceback (most recent call last):
File "indir.py", line 50, in <module>
audio.save()
File "/usr/local/lib/python3.6/dist-packages/mutagen/_util.py", line 169, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/mutagen/_util.py", line 140, in wrapper
return func(self, h, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/mutagen/flac.py", line 847, in save
self._save(filething, self.metadata_blocks, deleteid3, padding)
File "/usr/local/lib/python3.6/dist-packages/mutagen/flac.py", line 864, in _save
metadata_blocks, available, content_size, padding)
File "/usr/local/lib/python3.6/dist-packages/mutagen/flac.py", line 154, in _writeblocks
data += cls._writeblock(block)
File "/usr/local/lib/python3.6/dist-packages/mutagen/flac.py", line 126, in _writeblock
datum = block.write()
File "/usr/local/lib/python3.6/dist-packages/mutagen/flac.py", line 620, in write
f.write(self.data)
TypeError: a bytes-like object is required, not 'str'
My Code:
audio = FLAC("music.flac")
audio['artist'] = sarki.artist.name
audio['title'] = sarki.name
pic = Picture()
pic.type = id3.PictureType.COVER_FRONT
pic.width = 640
pic.height = 640
pic.mime = 'image/jpeg'
pic.data = "music.jpg"
audio.add_picture(pic)
audio.save()
I believe the error is here:
pic.data = "music.jpg"
You are attempting to set the image data of the picture to be a string. I'm guessing you wanted to set the image data to be the contents of the file music.jpg instead. If so, try replacing this line with the following two:
with open("music.jpg", "rb") as f:
pic.data = f.read()
This follows an example in the Mutagen API reference.
I've a dictionary consisting of keys = word, value = Array of 300 float numbers.
I'm unable to use this dictionary in my pyspark UDF.
When size of this dictionary is 2Million keys it does not work. But when I reduce the size to 200K it works.
This is my code for the function to be converted to UDF
def get_sentence_vector(sentence, dictionary_containing_word_vectors):
cleanedSentence = list(clean_text(sentence))
words_vector_list = np.zeros(300)# 300 dimensional vector
for x in cleanedSentence:
try:
words_vector_list = np.add(words_vector_list, dictionary_containing_word_vectors[str(x)])
except Exception as e:
print("Exception caught while finding word vector from Fast text pretrained model Dictionary: ",e)
return words_vector_list.tolist()
This is my UDF
get_sentence_vector_udf = F.udf(lambda val: get_sentence_vector(val, fast_text_dictionary), ArrayType(FloatType()))
This is how i'm calling the udf to be added as a column in my dataframe
dmp_df_with_vectors = df.filter(df.item_name.isNotNull()).withColumn("sentence_vector", get_sentence_vector_udf(df.item_name))
And this is the stack trace for the error
Traceback (most recent call last):
File "/usr/lib/spark/python/pyspark/broadcast.py", line 83, in dump
pickle.dump(value, f, 2)
SystemError: error return without exception set
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/spark/python/pyspark/sql/functions.py", line 1957, in wrapper
return udf_obj(*args)
File "/usr/lib/spark/python/pyspark/sql/functions.py", line 1916, in __call__
judf = self._judf
File "/usr/lib/spark/python/pyspark/sql/functions.py", line 1900, in _judf
self._judf_placeholder = self._create_judf()
File "/usr/lib/spark/python/pyspark/sql/functions.py", line 1909, in _create_judf
wrapped_func = _wrap_function(sc, self.func, self.returnType)
File "/usr/lib/spark/python/pyspark/sql/functions.py", line 1866, in _wrap_function
pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
File "/usr/lib/spark/python/pyspark/rdd.py", line 2377, in _prepare_for_python_RDD
broadcast = sc.broadcast(pickled_command)
File "/usr/lib/spark/python/pyspark/context.py", line 799, in broadcast
return Broadcast(self, value, self._pickled_broadcast_vars)
File "/usr/lib/spark/python/pyspark/broadcast.py", line 74, in __init__
self._path = self.dump(value, f)
File "/usr/lib/spark/python/pyspark/broadcast.py", line 90, in dump
raise pickle.PicklingError(msg)
cPickle.PicklingError: Could not serialize broadcast: SystemError: error return without exception set
How big is your fast_text_dictionary in the 2M case? It might be too big.
Try broadcast it first before running udf. e.g.
broadcastVar = sc.broadcast(fast_text_dictionary)
Then use broadcastVar instead in your udf.
See the document for broadcast
I am getting an error when creating a series in pandas.
Whenever I try to print the series I have created, I get an error.
The code I am running:
import pandas as pd
data2 = [1,2,3,4]
index = ['a','b','c','d']
s = pd.Series(data2, index)
print(s.shape)
s
The error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
s
File "C:\Python34\lib\idlelib\rpc.py", line 611, in displayhook
text = repr(value)
File "C:\Python34\lib\site-packages\pandas\core\base.py", line 80, in __repr__
return str(self)
File "C:\Python34\lib\site-packages\pandas\core\base.py", line 59, in __str__
return self.__unicode__()
File "C:\Python34\lib\site-packages\pandas\core\series.py", line 1060, in __unicode__
width, height = get_terminal_size()
File "C:\Python34\lib\site-packages\pandas\io\formats\terminal.py", line 33, in get_terminal_size
return shutil.get_terminal_size()
File "C:\Python34\lib\shutil.py", line 1071, in get_terminal_size
size = os.get_terminal_size(sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'
Your error is related to pyshell, not to pandas.
Try to run it through python directly or jupyter console, because the code you provided is correct.
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'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!?