'method' object is not subscriptable erroor - python

i write this code in vscode :
from fileinput import filename
import imp
import cv2,time,os,tensorflow as tf
import numpy as np
from tensorflow.python.keras.utils.data_utils import get_file
np.random.seed(123)
class Detector:
def __init__(self) -> None:
pass
def readClaassees(self,classesFilePath):
with open(classesFilePath,'r') as f:
self.classesList = f.read().splitlines()
#colors list
self.colorList =np.random.uniform(low=0,high=255,size=(len(self.classesList),3))
print(len(self.classesList),len(self.colorList))
def downloadModel(self,modelURL):
fileName= os.path.basename(modelURL)
self.modelName =fileName[:fileName.index('.')]
self.cacheDir ="./pretrained_model"
os.makedirs(self.cacheDir,exist_ok=True)
get_file(fname=fileName,origin=modelURL,cache_dir=self.cacheDir,cache_subdir="checkpoints",extract=True)
def loadModel(self):
print("Loading Model "+self.modelName)
#tf.keras.backend.clear_session()
self.model = tf.saved_model.load(os.path.join(self.cacheDir,"checkpoints",self.modelName,"saved_model"))
print("Model"+self.modelName+"loaded successfully...")
def createBoundinBox(self,image):
inputTensor = cv2.cvtColor(image.copy(),cv2.COLOR_BGR2RGB)
inputTensor = tf.convert_to_tensor(inputTensor,dtype=tf.uint8)
inputTensor = inputTensor[tf.newaxis,...]
detections = self.model(inputTensor)
bboxs = detections['detection_boxes'][0].numpy()
classIndexes = detections['detection_classes'][0].numpy().astype(np.int32)
classScores = detections['detection_scores'][0].numpy
imH,imW,imC =image.shape
if len(bboxs) != 0 :
for i in range(0,len(bboxs)):
bbox = tuple(bboxs[i].tolist())
classConfidence = classScores[i]
classIndex = classIndexes[i]
classLblelText = self.classesList[classIndex]
classColor = self.colorList[classIndex]
displayText ='{}: {}%'.format(classLblelText,classConfidence)
ymin, xmin, ymax, xmax = bbox
print(ymin,xmin,ymax,xmax)
break
def pedictImage(self,imagePath):
image = cv2.imread(imagePath)
self.createBoundinBox(image)
cv2.imshow("result",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
and i got this error after run the method self.createBoundinBox(image) in the main:
File "d:\TensorflowObjectDetection\Detector.py", line 60, in createBoundinBox
classConfidence = classScores[i]
TypeError: 'method' object is not subscriptable.
does anyone know how to solve it ,please help .

I think its because you forgot the brackets in this line
classScores = detections['detection_scores'][0].numpy
I think it should be:
classScores = detections['detection_scores'][0].numpy()
When you call it without the brackets you are calling a method or a function which you cannot subscript like this method[]. That is what the error is telling you.

I'm going to take a wild guess here, and say that the line that declares classScores, which is currently this:
classScores = detections['detection_scores'][0].numpy
should be this:
classScores = detections['detection_scores'][0].numpy().astype(np.int32)
in this context, the .numpy is a method that you call, which itself is not subscriptable, meaning that you can't use index notation on it. This makes sense because again, it's a method, and not an array or list or whatever.

Related

TF2 transform can't find an actuall existing frame

In a global planner node that I wrote, I have the following init code
#!/usr/bin/env python
import rospy
import copy
import tf2_ros
import time
import numpy as np
import math
import tf
from math import sqrt, pow
from geometry_msgs.msg import Vector3, Point
from std_msgs.msg import Int32MultiArray
from std_msgs.msg import Bool
from nav_msgs.msg import OccupancyGrid, Path
from geometry_msgs.msg import PoseStamped, PointStamped
from tf2_geometry_msgs import do_transform_point
from Queue import PriorityQueue
class GlobalPlanner():
def __init__(self):
print("init global planner")
self.tfBuffer = tf2_ros.Buffer()
self.listener = tf2_ros.TransformListener(self.tfBuffer)
self.drone_position_sub = rospy.Subscriber('uav/sensors/gps', PoseStamped, self.get_drone_position)
self.drone_position = []
self.drone_map_position = []
self.map_sub = rospy.Subscriber("/map", OccupancyGrid, self.get_map)
self.goal_sub = rospy.Subscriber("/cell_tower/position", Point, self.getTransformedGoal)
self.goal_position = []
self.goal = Point()
self.goal_map_position = []
self.occupancy_grid = OccupancyGrid()
self.map = []
self.p_path = Int32MultiArray()
self.position_pub = rospy.Publisher("/uav/input/position", Vector3, queue_size = 1)
#next_movement in
self.next_movement = Vector3
self.next_movement.z = 3
self.path_pub = rospy.Publisher('/uav/path', Int32MultiArray, queue_size=1)
self.width = rospy.get_param('global_planner_node/map_width')
self.height = rospy.get_param('global_planner_node/map_height')
#Check whether there is a path plan
self.have_plan = False
self.path = []
self.euc_distance_drone_goal = 100
self.twod_distance_drone_goal = []
self.map_distance_drone_goal = []
self.mainLoop()
And there is a call-back function call getTransformed goal, which will take the goal position in the "cell_tower" frame to the "world" frame. Which looks like this
def getTransformedGoal(self, msg):
self.goal = msg
try:
#Lookup the tower to world transform
transform = self.tfBuffer.lookup_transform('cell_tower', 'world', rospy.Time())
#transform = self.tfBuffer.lookup_transform('world','cell-tower' rospy.Time())
#Convert the goal to a PointStamped
goal_pointStamped = PointStamped()
goal_pointStamped.point.x = self.goal.x
goal_pointStamped.point.y = self.goal.y
goal_pointStamped.point.z = self.goal.z
#Use the do_transform_point function to convert the point using the transform
new_point = do_transform_point(goal_pointStamped, transform)
#Convert the point back into a vector message containing integers
transform_point = [new_point.point.x, new_point.point.y]
#Publish the vector
self.goal_position = transform_point
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException) as e:
print(e)
print('global_planner tf2 exception, continuing')
The error message said that
"cell_tower" passed to lookupTransform argument target_frame does not exist.
I check the RQT plot for both active and all, which shows that when active, the topic /tf is not being subscribe by the node global planner. Check the following image, which is for active
enter image description here
and this image is for all the node (include non-active)
enter image description here
But I have actually set up the listner, I have another node call local planner that use the same strategy and it works for that node, but not for the global planner
I'm not sure why this is.
Try adding a timeout to your lookup_transform() function call, as your transformation may not be available when you need it:
transform = self.tfBuffer.lookup_transform('cell_tower', 'world',rospy.Time.now(), rospy.Duration(1.0))

Image for Canvas is not created

So I want a window that updates a shown picture after clicking.
It works fine as long as there is no further tk.Tk() instance (remove/add line 8 of the code below).
If one is created before, this error is raised:
line 29, in CreatePeakSelectionWindow
[...]
self.imgCanvas.create_image((0,0),anchor=tk.NW,image=self.img1)
[...]
_tkinter.TclError: image "pyimage1" doesn't exist
I think I need to pass some argument to Tk()?
I don't know where to even look to address this issue and understand how it is caused.
Sadly this widget is to be used to allow manual selection of some peaks and should be done in an external window.
FYI all arrays are dummies (random arrays) for simplicities sake.
Thank you very much for any help!
The code which causes the issue is the following:
import tkinter as tk
import numpy as np
from PIL import Image,ImageTk
import matplotlib.pyplot as plt
class Dummy:
def __init__(self):
self.MainWin = tk.Tk() #>this line causes the issue
imgs = np.random.randint(0,255,(512,624,2))
self.img = imgs[:,:,0] #self.img is a numpy array in black and white
self.imgSize = self.img.shape
self.peakList = np.array([[200,200],[300,400]])
self.selectedIndexOfPeaksList = []
self.peakListGenerated = True
def CreatePeakSelectionWindow(self):
if self.peakListGenerated:
self.selectedIndexOfPeaksList = []
self.PeakSelectionWindow = tk.Tk()
self.PeakSelectionWindow.protocol("WM_DELETE_WINDOW",self.PeakSelectionWindowClose)
self.PeakSelectionWindow.geometry("%sx%s"%(self.imgSize[1],self.imgSize[0]))
self.PeakSelectionWindow.title("Peak Slection")
self.img1 = ImageTk.PhotoImage(image=Image.fromarray(self.img))
self.imgCanvas = tk.Canvas(self.PeakSelectionWindow,width=self.imgSize[1],height=self.imgSize[0])
self.imgCanvas.place(x=0,y=0)
self.PeakSelectionWindow.bind("<Button 1>",self.LeftClick)
self.PeakSelectionWindow.bind("<Button 3>",self.RightClick)
self.PeakSelectionWindow.update()
self.imgCanvas.create_image((0,0),anchor=tk.NW,image=self.img1)
else:
print("List of peaks has not yet been generated!",file=sys.stderr)
def PeakSelectionWindowClose (self):
if len(self.selectedIndexOfPeaksList) > 0:
print("put extraction here")
#self.selectedPeaksEntry.insert(tk.END,", ".join(map(str,self.selectedIndexOfPeaksList)))
self.PeakSelectionWindow.destroy()
def LeftClick(self,event):
distance = np.sqrt((self.peakList[:,1]-event.x)**2+(self.peakList[:,0]-event.y)**2)
index = np.argmin(distance)
if index not in self.selectedIndexOfPeaksList:
self.peakList[index]
self.selectedIndexOfPeaksList += [index]
newImg = np.random.randint(0,255,(self.img.shape[0],self.img.shape[1],3))
self.PeakSelectionWindow.newImg = img = ImageTk.PhotoImage(image=Image.fromarray(newImg.astype("uint8"),mode="RGB"))
self.imgCanvas.delete("all")
self.imgCanvas.create_image((0,0),anchor=tk.NW,image=self.PeakSelectionWindow.newImg)
self.imgCanvas.update()
def RightClick (self,event):
distance = np.sqrt((self.peakList[:,1]-event.x)**2+(self.peakList[:,0]-event.y)**2)
index = np.argmin(distance)
print(self.selectedIndexOfPeaksList)
if index in self.selectedIndexOfPeaksList:
if len(self.selectedIndexOfPeaksList) > 1:
self.selectedIndexOfPeaksList.remove(index)
newImg = np.random.randint(0,255,(self.img.shape[0],self.img.shape[1],3))
self.PeakSelectionWindow.newImg = img = ImageTk.PhotoImage(image=Image.fromarray(newImg.astype("uint8"),mode="RGB"))
self.imgCanvas.delete("all")
self.imgCanvas.create_image((0,0),anchor=tk.NW,image=self.PeakSelectionWindow.newImg)
self.imgCanvas.update()
else:
self.selectedIndexOfPeaksList = []
self.PeakSelectionWindow.newImg = newImg = ImageTk.PhotoImage(image=Image.fromarray(self.img.astype("uint8")))
self.imgCanvas.delete("all")
self.imgCanvas.create_image((0,0),anchor=tk.NW,image=self.PeakSelectionWindow.newImg)
self.imgCanvas.update()
if __name__ == "__main__":
window = Dummy()
window.CreatePeakSelectionWindow()
tk.mainloop()
Okay so I found a solution.
The additional window needs to be a class with tk.Toplevel().
All changes for the code above are:
class Dummy: to class Dummy (tk.Toplevel()):
def __init__(self): to def __init__ (self,master):
self.peakSelectionWindow to self (as a reference to master
passed to the class)
any tk object (like buttons) also needs this master set as the window too to be rendered
Of course the creation of the first window should be handled outside of the class, passing the windowName = tk.Tk() onto the call of Dummy like a normal variable/reference.
In case you need to share variables of the master to this dummy class, I think windowName.variableName = 5 makes them known/accessable in dummy too (via self.variableName). However this might be messy, so instead pass them on normally if possible.

generating video using moviepy using image and text but getting ERROR like size = clips[0].size AttributeError: 'list' object has no attribute 'size'

import glob
import os
from natsort import natsorted
from moviepy.editor import *
base_dir = os.path.realpath("./images/")
print(base_dir)
gif_name = 'pic'
fps = 24
file_list = glob.glob('./images/*.jpg') # Get all the pngs in the current directory
file_list_sorted = natsorted(file_list,reverse=False) # Sort the images
clips = [ImageClip(m).set_duration(5)
for m in file_list_sorted]
print (clips)
text_list = ["Piggy", "Kermit", "Gonzo", "Fozzie"]
clip_list = []
for text in text_list:
try:
txt_clip = ( TextClip(text, fontsize = 70, color = 'white').set_duration(2))
clip_list.append(txt_clip)
except UnicodeEncodeError:
txt_clip = TextClip("Issue with text", fontsize = 70, color = 'white').set_duration(2)
clip_list.append(txt_clip)
print(clip_list)
final_clip = CompositeVideoClip([clips, clip_list])
final_clip.write_videofile("./video/export.mp4", fps = 24, codec = 'mpeg4')
But getting ERROR like size = clips[0].size
AttributeError: 'list' object has no attribute 'size'
i need to display image for first 15sec and after 15 sec text should be display 10 sec.
Hi thanks for posting the question. Hopefully this would be helpful.
Your main mistake concerns the following line:
final_clip = CompositeVideoClip([clips, clip_list])
CompositeVideoClip.__init__ expects a list of type Clip (CompositeVideoClip inherits the Clip class). However, in your previous lines:
print(clips)
...
print(clip_list)
so what you have effectively fed to the CompositeVideoClip.__init__ method is a nested list. So instead, you should do something like the following:
final_clip = CompositeVideoClip(clips + clip_list)
I'm sure you can come up with a more elegant solution, this is a working solution for you to start with. Do write further in case my proposal does not work.

How do I use a csv data as variables to apply it for a formula?

I'm trying to use data from a csv file ( https://www.kaggle.com/jingbinxu/sample-of-car-data ). I only need the horsepower and weight columns as variables for the equation: ( 1/4 mile et = 6.290 * (weight/hp) ** .33 ), but it won't apply it. I don't know if the storage is working or I shouldn't do it as a class. When I run the program it doesn't show any errors, but it doesn't show results either. Then I got to plot the results, but I don't think it's even calculating and storing results. Any help is appreciated. Thanks in advance.
Here's the current code i have:
import numpy as np
class car_race_analysis():
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename,delimiter= ',', skip_header = 1 )
def race_stats(self,w,h):
#cars in data
cars = np.unique(self.data[:,0])
#storage for output
race_times = []
#for each car
for car in cars:
#mask
mask = self.data[:,0] == car
#get data
w = self.data[mask,12]
h = self.data[mask,18]
#apply formula
qrtr_mile = 6.290 * ( w / h ) ** .33
race_times.append(qrtr_mile)
#new atribute
self.race_times = np.array(race_times)
print(race_times)
def trend_plotter(self):
import matlib.pyplot as plt
#inputs
self.race_stats
cars = np.unique(self.data[:,0])
#plot
plt.plot(cars,self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
filename = 'car_data.csv'
Two problems:
I think you meant matplotlib instead of matlib. Make sure you install it pip3 install matplotlib --user and edit your code accordingly.
Your previous code wasn't working because you weren't instantiating a class or running any methods. The only "work" your program did was to define the class and then set a filename variable.
To solve #2, replace your filename=... line with the code below.
Here's what it does:
It checks to see if the file is being run directly (i.e. from command prompt such as python3 <your_file_name>.py. If this class is being imported and used from a different python file, this code would not be executed. More reading: https://www.geeksforgeeks.org/what-does-the-if-name-main-do/
We instantiate a instance of your class and supply the filename variable since that it was your class' __init__ method expects.
We invoke the trend_plotter method on the instance of the class.
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
Even with those changes, your program will not work because it has other errors. I made a guess at fixing it, which I've pasted below, but I strongly encourage you do diff my changes to understand what I altered to be sure it does what you want.
import numpy as np
import matplotlib.pyplot as plt
class car_race_analysis():
race_times = []
cars = []
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename, delimiter=',', skip_header=1)
def race_stats(self, w, h):
#cars in data
self.cars = np.unique(self.data[:, 0])
# storage for output
self.race_times = []
# for each car
for car in self.cars:
# mask
mask = self.data[:, 0] == car
# get data
w = self.data[mask, 12]
h = self.data[mask, 18]
# apply formula
qrtr_mile = 6.290 * (w / h) ** .33
self.race_times.append(qrtr_mile)
# new atribute
self.race_times = np.array(self.race_times)
def trend_plotter(self):
# inputs
self.race_stats(len(self.cars), len(self.race_times))
# plot
plt.plot(self.cars, self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
plt.show()
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()

AttributeError: 'ResizeImage' object has no attribute 'thumbnail'

I'm making a class to make a nicer "thumbnail" for a picture.
The functions works fine, but inside the class I got the "object" has no "attribute 'thumbnail'". I'm not an expert on classes, but maybe a short recommendation? The "open" method worked fine!
class ResizeImage:
from PIL import Image
def newImage(self,dimensiune):
NouaPoza = Image.new('RGBA', (dimensiune, dimensiune), (255, 255, 255, 0))
self.thumbnail((dimensiune, dimensiune), Image.ANTIALIAS)
coordonateCentrare = ((dimensiune - self.size[0]) // 2, (dimensiune - self.size[1]) // 2)
NouaPoza.paste(self,coordonateCentrare)
return NouaPoza
def openVechi(self,fisier_in):
self = Image.open(fisier_in)
return self
def saveNou(self,fisier_out):
self.save(fisier_out)
if __name__ == '__main__':
fisier_in = "[...]"
fisier_out = "[...]"
poza = ResizeImage()
poza.openVechi(fisier_in)
poza.newImage(500)
poza.saveNou(fisier_out)
Thank you in advance!
P.S. Working just with functions was ok, like:
def thumbnail(poza,dimensiune):
poza.thumbnail((dimensiune,dimensiune),Image.ANTIALIAS)
EDIT
I believe the right declaration is:
class ResizeImage(Image.Image):
def newImage(self,dimensiune):
self.thumbnail((dimensiune,dimensiune),Image.ANTIALIAS)
BUT I get the following error:
File "C:/Users/claudiu.ivanescu/PycharmProjects/eDX/NewImage.py", line 11, in newImage
self.thumbnail((dimensiune,dimensiune),Image.ANTIALIAS)
File "C:\Users\claudiu.ivanescu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2059, in thumbnail
x, y = self.size
AttributeError: 'ResizeImage' object has no attribute 'size'
After some researching I renounce to make the class as before. I put all the details as attributes for object. And all the other method I access them without args.
There is the new class:
class resizeImage:
def __init__(self,dimension,fileIn,fileOut)
[...]
def createThumbnail(self):
from PIL import Image
picture = Image.open(self.fileIn)
[...]
thumbnail.save(self.fileOut)
def delThumbnail(self):
import os,sys
os.remove(self.fileOut)
Maybe will be useful for some people!

Categories

Resources