Python Error in Displaying Image - python

On this Image
I am trying to apply:
from PIL import Image
img0 = PIL.Image.open('Entertainment.jpg')
img0 = np.float32(img0)
showarray(img0/255.0)
And I get this error:
TypeErrorTraceback (most recent call last)
<ipython-input-20-c181acf634a8> in <module>()
2 img0 = PIL.Image.open('Entertainment.jpg')
3 img0 = np.float32(img0)
----> 4 showarray(img0/255.0)
<ipython-input-8-b253b18ff9a7> in showarray(a, fmt)
11 f = BytesIO()
12 PIL.Image.fromarray(a).save(f, fmt)
---> 13 display(Image(data=f.getvalue()))
14
15 def visstd(a, s=0.1):
TypeError: 'module' object is not callable
I can't understand why.
What is not callable here?
How can I just display the image?

Image is a module that you imported
from PIL import Image
You can't call it
Image(data=f.getvalue())
There's a show method that may be useful
img0 = PIL.Image.open('Entertainment.jpg')
img0.show()

The problem may stem from how you've imported the display() function. If your import line is:
import IPython.display as display
then you need to invoke display.display() to show the image. For example:
import IPython.display as display
my_image = Image.open('something.jpg')
display.display(my_image)
If you instead invoke the function as
import IPython.display as display
my_image = Image.open('something.jpg')
display(my_image) # INCORRECT
# TypeError: 'module' object is not callable
then you will indeed get the error message in your original post because display is referring to a module, not a function.
Alternatively, if you import the display() function in the following manner, your code will work:
from IPython.display import display
my_image = Image.open('something.jpg')
display(my_image)

Related

Requests not defined after importing from a file

I have imported a file image_function.py to my notebook. However when i tried using one of the functions im_reverse, it gave me an error.
Code:
import image_function
image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-61-afc744ac8a12> in <module>()
1 import image_function
----> 2 image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
/content/image_function.py in im_reverse(image_path, reverse, url)
45 mat_image_column_reverse[c][i] = mat_image_reverse[j][i]
46 c += 1
---> 47
48 plt.axis('off')
49
NameError: name 'requests' is not defined
The error happened before it reached the code for reversing vertically, which is down below.
What's inside image_function:
#libraries:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import imshow
from PIL import Image
import copy
import requests
from io import BytesIO
This is the code after the error:
def im_reverse(image_path, reverse = 'horizontal', url = True):
if url == True:
response = requests.get(image_path)
with Image.open(BytesIO(response.content)) as image:
mat_image = np.array(image, dtype=int)
m, n, depth = mat_image.shape
if reverse == 'horizontal':
mat_image_reverse = copy.deepcopy(mat_image)
mat_image_rows_reverse = copy.deepcopy(mat_image)
for i in range(m):
c = 0
for j in range(n-1,-1,-1):
mat_image_rows_reverse[i][c] = mat_image_reverse[i][j]
c += 1
plt.axis('off')
return imshow(mat_image_rows_reverse)
I have tried a lot of solutions on the web. However i dont see anything wrong. I have also tried a deliberate from requests import get or !pip install requests and it still didn't work.
Can anyone please offer a solution. Thanks
It sounds like you need to install requests:
python3 -m pip install requests

PythonCV2 NoneType Object

#!/usr/bin/env python
'''
Usage:
./ssearch.py input_image (f|q)
f=fast, q=quality
Use "l" to display less rects, 'm' to display more rects, "q" to quit.
'''
import sys
import cv2
if __name__ == '__main__':
# If image path and f/q is not passed as command
# line arguments, quit and display help message
if len(sys.argv) < 3:
print(__doc__)
sys.exit(1)
# speed-up using multithreads
cv2.setUseOptimized(True);
cv2.setNumThreads(4);
# read image
im = cv2.imread(sys.argv[1])
# resize image
newHeight = 200
newWidth = int(im.shape[1]*200/im.shape[0])
im = cv2.resize(im, (newWidth, newHeight))
Here i am getting error
AttributeError Traceback (most recent call last)
<ipython-input-7-b88f466ecb3b> in <module>
25 # resize image
26 newHeight = 200
---> 27 newWidth = int(im.shape[1]*200/im.shape[0])
28 im = cv2.resize(im, (newWidth, newHeight))
29
AttributeError: 'NoneType' object has no attribute 'shape'
and explain cv2.imread(sys,argv[1]) line
(2)second question is how do i get nonetype error because i havent
passed my image path from my command line yet
(3) cmd line didnt prompt because program didnt executed with th error
i am sorry i couldnt place entire code
The correct way is:
# read image
im = cv2.imread(sys.argv[1])
if im == None :
sys.exit('Invalid or missing image: ' + sys.argv[1])
BEFORE you try to do anything with your image im.

Python callback attribute error

I have written a python ROS node to subscribe to two different topics and uses the ApproximateTimeSynchroniser to basically to match the messages via their timestamp and bundle these messages into one callback routine. If I use the callback to simply print out the two messages received it works fine.
However, I would like to populate a geometry_msgs/Pose message using the x and y positions from the received Pose 2D data in the callback routine.Using the code below, I have done this by making an empty Pose object in the callback routine:
#!/usr/bin/env python
import message_filters
import rospy
from laser_line_extraction.msg import LineSegmentList
from geometry_msgs.msg import Pose, Pose2D
from std_msgs.msg import Int32, Float32
rospy.init_node('simul-subscriber')
def callback(Pose2D, LineSegmentList):
pose = Pose()
pose.position.x = Pose2D.position.x
pose.position.y = Pose2D.position.y
pose.position.z = 0
#print(Pose2D, LineSegmentList, pose)
print(pose)
print(LineSegmentList)
line_segment_sub = message_filters.Subscriber('/line_segments', LineSegmentList)
pose_2D_sub = message_filters.Subscriber('/pose2D',Pose2D)
ts = message_filters.ApproximateTimeSynchronizer([line_segment_sub, pose_2D_sub], 10, 0.1, allow_headerless=True)
ts.registerCallback(callback)
rospy.spin()
Unfortunately, this gives a weird error when running this node:
[ERROR] [1535552711.709928, 1381.743000]: bad callback: <bound method Subscriber.callback of <message_filters.Subscriber object at 0x7f7af3cee9d0>>
Traceback (most recent call last):
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
cb(msg)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/message_filters/__init__.py", line 75, in callback
self.signalMessage(msg)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/message_filters/__init__.py", line 57, in signalMessage
cb(*(msg + args))
File "/opt/ros/kinetic/lib/python2.7/dist-packages/message_filters/__init__.py", line 287, in add
self.signalMessage(*msgs)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/message_filters/__init__.py", line 57, in signalMessage
cb(*(msg + args))
File "/home/elisabeth/catkin_ws/src/hector_quadrotor/hector_quadrotor_demo/python_scripts/simul-subscriber.py", line 14, in callback
pose.position.x = Pose2D.position.x
AttributeError: 'LineSegmentList' object has no attribute 'position'
This is odd as the position attribute is only referenced for the Pose 2D and not the LineSegmentList msg. I suspect this is most a python issue than a ROS issue, any help somebody could give would be much appreciated!
I am following the example found at http://wiki.ros.org/message_filters where they took two different topics image and cameraInfo and passed them into the callback function
1 import message_filters
2 from sensor_msgs.msg import Image, CameraInfo
3
4 def callback(image, camera_info):
5 # Solve all of perception here...
6
7 image_sub = message_filters.Subscriber('image', Image)
8 info_sub = message_filters.Subscriber('camera_info', CameraInfo)
9
10 ts = message_filters.TimeSynchronizer([image_sub, info_sub], 10)
11 ts.registerCallback(callback)
12 rospy.spin()
You confuse class names with object names.
The fix to your program should be straight forward.
I've changed Pose2D to pose2d, and LineSegmentList to linesegmentlist where it was necessary and comented it with # --- Change ...:
#!/usr/bin/env python
import message_filters
import rospy
from laser_line_extraction.msg import LineSegmentList
from geometry_msgs.msg import Pose, Pose2D
from std_msgs.msg import Int32, Float32
rospy.init_node('simul-subscriber')
# --- CHANGE: using proper object names instread of class names
def callback(pose2d, linesegmentlist):
pose = Pose()
# --- CHANGE: using the object
pose.position.x = pose2d.position.x
pose.position.y = pose2d.position.y
pose.position.z = 0
#print(pose2d, linesegmentlist, pose)
print(pose)
print(linesegmentlist)
line_segment_sub = message_filters.Subscriber('/line_segments', LineSegmentList)
pose_2D_sub = message_filters.Subscriber('/pose2D',Pose2D)
ts = message_filters.ApproximateTimeSynchronizer([line_segment_sub, pose_2D_sub], 10, 0.1, allow_headerless=True)
ts.registerCallback(callback)
rospy.spin()

AttributeError: 'builtin_function_or_method' object has no attribute 'detectMultiScale'

This is the code
import cv2, sys
from numpy import array
img = cv2.imread(sys.argv[1])
img2 = array( 200 * (img[:,:,2] > img[:,:, 1]), dtype='uint8')
objects = cv2.CascadeClassifier.detectMultiScale(img2)
print (objects)
I have the error in the title at line 5. (I have tried also with cv2.CascadeClassifier.detectMultiScale(img) and I have the same error).
Many thanks!
You have to call the function detectMultiScale() on an instance of CascadeClassifier()
cascade = cv2.CascadeClassifier()
objects = cascade.detectMultiScale(img2)

Python: AttributeError

When I run my script I get this error:
File "test_cm.py", line 34, in
labels = labels_img.get_data() AttributeError: 'tuple' object has no attribute 'get_data'
from dipy.tracking.eudx import EuDX
from dipy.reconst import peaks, shm
from dipy.tracking import utils
from dipy.data import read_stanford_labels
from dipy.io.gradients import read_bvals_bvecs
import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
source="prova11/"
path=source
print('loading data')
bvals,bvecs=read_bvals_bvecs(source+"bvals",source+"bvecs")
bvals[bvals < 10] = 0
img = nib.load(source+"segment-TO-b0.nii")
data = img.get_data()
affine=img.affine
labels_img = read_stanford_labels()
labels = labels_img.get_data()
read_stanford_labels() returns a tuple, and tuples don't have a get_data() method which is why the error says AttributeError: 'tuple' object has no attribute 'get_data'.
You should go over your read_stanford_labels function and see why it returns a tuple, which isn't what you expected.
Edit: By going over the documentation/example your code should be
hardi_img, gtab, labels_img = read_stanford_labels() instead of
labels_img = read_stanford_labels().
Alternatively, if you don't need the first 2 values, you can use
labels_img = read_stanford_labels()[-1] or
*_, labels_img = read_stanford_labels().

Categories

Resources