Python: AttributeError - python

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().

Related

how to solve theproblem about:TypeError: __init__() missing 1 required positional argument: 'image_index' [duplicate]

This question already has answers here:
__init__() missing 1 required positional argument
(6 answers)
Closed 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I try my best to finish my code, but i find a error that i can't slove, in my code i already write down the image_index,but the error can't slove, so i want to ask for you, thank you so much!
this is the code:
import numpy as np
import torch
from torch.utils.data import Dataset
import glob
from PIL import Image
from torchvision import transforms
from skimage.segmentation import mark_boundaries
from torchvision.transforms.functional import to_pil_image
from torchvision.transforms.transforms import Grayscale, RandomHorizontalFlip, Resize, ToTensor
import numpy as np
import matplotlib.pyplot as plt
import os
class InfraredDataset(Dataset):
def __init__(self, dataset_dir, image_index):
super(InfraredDataset, self).__init__()
self.dataset_dir = dataset_dir
self.image_index = image_index
self.transformer = transforms.Compose([
Resize((256, 256)),
Grayscale(),
ToTensor(),
RandomHorizontalFlip(0.5),
])
def __getitem__(self, index):
image_index = self.image_index[index].strip('\n')
image_path = os.path.join(self.dataset_dir, 'images', '%s.png' % image_index)
label_path = os.path.join(self.dataset_dir, 'masks', '%s_pixels0.png' % image_index)
image = Image.open(image_path)
label = Image.open(label_path)
torch.manual_seed(1024)
tensor_image = self.transformer(image)
torch.manual_seed(1024)
label = self.transformer(label)
label[label > 0] = 1
return tensor_image, label
def __len__(self):
return len(self.image_index)
if __name__ == "__main__":
f = open('../sirst/idx_427/trainval.txt').readlines()
ds = InfraredDataset(f)
# 数据集测试
for i, (image, label) in enumerate(ds):
image, label = to_pil_image(image), to_pil_image(label)
image, label = np.array(image), np.array(label)
print(image.shape, label.shape)
vis = mark_boundaries(image, label, color=(1, 1, 0))
image, label = np.stack([image] * 3, -1), np.stack([label] * 3, -1)
plt.imsave('image_%d.png' % i, vis)
this is error:
Traceback (most recent call last):
File "H:/ProgramData/Infrared-detect-by-segmentation-master/Infrared-detect-by-segmentation-master/utils/dataloader.py", line 54, in <module>
ds = InfraredDataset(f)
TypeError: __init__() missing 1 required positional argument: 'image_index'
i can't understand that why i made the mistake,so i add the image_imdex but can't slove the problem.
It looks like you're missing to pass the second argument when instantiating the InfraredDataset object (named ds). As you can see the __init__() requires two arguments: dataset_dir, image_index.
In the second piece of code, you are instantiating the object as ds = InfraredDataset(f) passing only one argument (f, which will be taken from the __init__() as the dataset_dir parameter).
In conclusion, you need to match the number and position of the arguments of the __init__() with the ones you use for creating an object. You need either to pass another argument when creating the object, or to make the __init__() accepting only one.

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()

'NoneType' object has no attribute 'fileno'

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
plt.style.use('ggplot')
columns = ['user_id','order_dt','order_products','order_amount']
df = pd.read_csv('CDNOW_master.txt',names = columns,sep = '\s+')
df['order_date'] = pd.to_datetime(df.order_dt,format='%Y%m%d')
df['month'] = df.order_date.values.astype('datetime64[M]')
f = df.groupby('user_id')['month'].min().value_counts()
print(f)
Above is my code,my purpose is to get the value_counts of the users purchased in their first month, but only got the result of 'NoneType' object has no attribute 'fileno'.
any ideas? much appreciate
here are the traceback
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\practice\CDNOW.py", line 19, in <module>
print(f)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\base.py", line 51, in __str__
return self.__unicode__()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\series.py", line 982, in __unicode__
width, height = get_terminal_size()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\io\formats\terminal.py", line 33, in get_terminal_size
return shutil.get_terminal_size()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 1071, in get_terminal_size
size = os.get_terminal_size(sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'
I am seeing this as well.
>>> type(sys.__stdout__)
<class 'NoneType'>
I get NoneType when calling dunder stdout while I am using idle. I assume that pandas wants to determine how much to display in the results and is looking for the sys output information. In the documentation, it mentions what this is, but not how to reset it.
I did this:
sys.__stdout__ = sys.stdout
and it fixed the problem, but I have not idea if I caused problems down the line.
You may wish to try out the following.
df = pd.read_csv('CDNOW_master.txt',usecols = columns,sep = '\s+')
instead of
df = pd.read_csv('CDNOW_master.txt',names = columns,sep = '\s+')
This solved my problem. Hope it solves yours too.

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 Error in Displaying Image

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)

Categories

Resources