I am using the following Python script:
import numpy as np
import matplotlib.pyplot as plt
import nibabel
import os
def collapse_probtrack_results(waytotal_file, matrix_file):
with open(waytotal_file) as f:
waytotal = int(f.read())
data = nibabel.load(matrix_file).get_data()
collapsed = data.sum(axis=0) / waytotal * 100.
return collapsed
matrix_template = 'results/{roi}.nii.gz.probtrackx2/matrix_seeds_to_all_targets.nii.gz'
processed_seed_list = [s.replace('.nii.gz','').replace('label/', '')
for s in open('/home/salvatore/tirocinio/aal_rois_diff_space/aal.txt').read().split('\n')
if s]
N = len(processed_seed_list)
conn = np.zeros((N, N))
rois=[]
idx = 0
for roi in processed_seed_list:
matrix_file = template.format(roi=roi)
seed_directory = os.path.dirname(result)
roi = os.path.basename(seed_directory).replace('.nii.gz.probtrackx2', '')
waytotal_file = os.path.join(seed_directory, 'waytotal')
rois.append(roi)
try:
# if this particular seed hasn't finished processing, you can still
# build the matrix by catching OSErrors that pop up from trying
# to open the non-existent files
conn[idx, :] = collapse_probtrack_results(waytotal_file, matrix_file)
except OSError:
pass
idx += 1
# figure plotting
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(conn, interpolation='nearest', )
cax.set_cmap('hot')
caxes = cax.get_axes()
When I try to run it I get the following error: NameError: name 'template' is not defined. This refers to line 22 of the script above. Can you please help me to figure out what is this about?
There is no variable like template, so template cannot be used in the right side of the expression. Try
matrix_file = matrix_template.format(roi=roi)
instead.
Related
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.
i have the below posted coordinates but in wkt formate and i want to write to a file as shapefile.when i run the code i receive the error:
TypeError: object of type 'float' has no len()
after placing some logs for debugging, i found that, the methond bindPolygonCoordinates returns nothing
please let me know how correctly export coordinates to a shapefile.
code
def extractLonLatFromPolygonInWKTFor(polygonInWKT):
lons = []
lats = []
s = polygonInWKT.replace("POLYGON","")
s = s.replace("((","")
s = s.replace("))","")
s = s.strip()
lonsLats = s.split(",")
for i in range (0,len(lonsLats)):
lonLat = lonsLats[i].strip()
lonLat = lonLat.split(" ")
lons.append(float(lonLat[0]))
lats.append(float(lonLat[1]))
return lons,lats
def bindPolygonCoordinates(longitudeValuesArray, latitudeValuesArray):
return Polygon(zip(longitudeValuesArray, latitudeValuesArray))
def buildGeoDataFrameForGeometry(geometry):
crs = {'init': 'epsg:4326'}
return gpd.GeoDataFrame(index=[0], crs=crs, geometry=[geometry])
lons,lats = extractLonLatFromPolygonInWKTFor(fieldCoordinatesAsTextInWKTInEPSG4326)
boundingPolygonGeometry = bindPolygonCoordinates(lons, lats)#returns nothing
boundingGeometryAsGDF = buildGeoDataFrameForGeometry(boundingPolygonGeometry)
coords:
fieldCoordinatesAsTextInWKTInEPSG4326:POLYGON((6.692790084436616 51.13237486727857,6.6918971115756305 51.132725423664596,6.6922145189906725 51.13301489625002,6.6926758177672 51.13291397940796,6.692650425173997 51.1327121450621,6.692430356032901 51.132520932762816,6.692790084436616 51.13237486727857))
lonsLats:['6.741879696309871 51.08423775429969', '6.742907378503366 51.08158745820981', '6.746964018740842 51.08233499299334', '6.746152690693346 51.08440763989611', '6.741879696309871 51.08423775429969']
as per other comment, use shapely.wky.loads()
no need to hand code parsing standard format
generating a .shp file is then done by geopandas
import shapely.wkt
import geopandas as gpd
from pathlib import Path
fieldCoordinatesAsTextInWKTInEPSG4326 = "POLYGON((6.692790084436616 51.13237486727857,6.6918971115756305 51.132725423664596,6.6922145189906725 51.13301489625002,6.6926758177672 51.13291397940796,6.692650425173997 51.1327121450621,6.692430356032901 51.132520932762816,6.692790084436616 51.13237486727857))"
f = Path.cwd().joinpath("shape_dir")
if not f.is_dir(): f.mkdir()
f = f.joinpath("shape.shp")
gpd.GeoDataFrame(geometry=[shapely.wkt.loads(fieldCoordinatesAsTextInWKTInEPSG4326)]).to_file(str(f))
Currently trying to pull up figures that go with a response, whenever I open the figure (plt.draw) it pans focus to the picture and the user has to click back to the terminal each time the picture is called. I am trying to get it where the figure is a background object (so it will open but it won't shift focus) or possibly manually shift the Foreground Window to the terminal or the file name the code is running on. Also trying to make it linux and windows friendly so can't be windows specific commands, but anything helps. My code is provided below:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import warnings
warnings.filterwarnings("ignore")
def ShowImageCommon(wintitle = "", imgpath = "", imgtitle = "", imgshowdelay = 5):
ImageAddress = imgpath
ImageItself = Image.open(ImageAddress)
ImageNumpyFormat = np.asarray(ImageItself)
plt.title(imgtitle)
figure = plt.gcf()
# figure.set_visible(not figure.get_visible())
figure.canvas.set_window_title(wintitle)
axis = plt.gca()
x_axis = axis.axes.get_xaxis()
x_axis.set_visible(False)
y_axis = axis.axes.get_yaxis()
y_axis.set_visible(False)
plt.show()
return ImageNumpyFormat
def ShowImageInteractive(wintitle = "", imgpath = "", imgtitle = "", imgpause = 0):
while True:
try:
ImageNumpyFormat = ShowImageCommon(wintitle, imgpath, imgtitle)
plt.imshow(ImageNumpyFormat)
plt.draw()
plt.pause(0.1) # Window closes after specified delay in sec
return plt
except:
imgpath = input(f'Could not open image path {imgpath}, please type path here >> ')
def main():
imgpause = 0.1
wintitle = 'UIB Functional Test'
imgpath = '{path to file}/Keypad Press Sequence.png'
imgtitle = 'Keypad Press Sequence'
plt = ShowImageInteractive(wintitle, imgpath, imgtitle, imgpause)
y_n= input("is this clear? >> ") # want focus back to terminal to answer question
if __name__ == "__main__":
main()
Also any suggestions for labeling windows and opening them are greatly appreciated but again, Linux friendly!
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()
I'm new to the world of python. I'm trying to create a plot showing accumulated GDD (Growing degree days) vs time for selected cities within a given period of time
I wrote a function to accomplish this, but I can't seem to get it to work right. I keep getting with an empty plot in it. Also a dimension error. Anyone know how i can solve these issues.
Any help/suggestions is appreciated!
Here is the code
import sys, argparse, csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
def open_file(file_name, mode):
"""Open a file."""
try:
with open(sys.argv[1], 'r') as the_file:
filename=the_file.read()
except IOError as err:
print("Unable to open the file", file_name, "Ending program.\n", err)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return filename
"""Cities.txt file as an argument"""
try:
my_file = open_file(sys.argv[1], 'r')
except:
print("GDD needs one argument", "\nEnding program...\n")
input("Press the enter key to exit.")
sys.exit()
extension=".csv"
for line in my_file.splitlines():
file_name=line+extension
print(file_name)
with open('data/'+ file_name, "rU") as files:
val = list(csv.DictReader(files))
l = []
for i in range(0, len(val)):
row = val[i]
if row['Min Temp'] == '' or row['Max Temp'] == '':
pass
else:
GDD = ((float(row['Min Temp']) + float(row['Max Temp']))/2)-10
l.append(GDD)
val[i]['GDD'] = GDD
#print(row['Min Temp'], ' ' , row['Max Temp'], ' ', str(round(row['GDD'], 2)))
#plt.subplot(1,1,1)
#x = np.linspace(1, 12, 365, endpoint=True)
x = np.linspace(1, 12, 365, endpoint=True)
plt.plot(x,GDD, label = file_name.split(',')[0])
plt.gcf().autofmt_xdate()
plt.legend(loc="upper left")
plt.xlabel('Months', color='black')
plt.ylabel('Cumulative GDD (>10°C)')
plt.title('Accumulated Growing Degree Days')
plt.draw()
A simple and fast solution could be to add plt.hold(True) after a plot call.
A more clean solution is to use a figure which can bee seen as window which you draw onto. just like in this example
So you'd define a figure, keep its reference, add axes and perform all action on these axes
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax.plot(...)