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))
Related
I have 180 .nii fMRI images for each patient and I need to flip them from right to left. I've tried using 'for' statement to batch processing these images. But it seems like The following code only produce one result.
Here is the following code:
import nibabel as nib
import numpy as np
import os
NII_DIR='/Users/lena/testtest'
def get_filelist(dir, Filelist):
if os.path.isdir(dir):
for s in os.listdir(dir):
newDir = os.path.join(dir, s)
Filelist.append(newDir)
return Filelist
list = get_filelist(NII_DIR, [])
print(len(list))
type(list)
for i in list:
def read_nii_file1(nii_path):
nii_img=nib.load(nii_path)
return nii_img
nii_img=read_nii_file1(os.path.join(i))
from nilearn.image import new_img_like
print(nii_img.affine.shape)
print(nii_img.affine)
def flip_image(image, axis):
try:
new_data = np.copy(image.get_fdata())
for axis_index in axis:
new_data = np.flip(new_data, axis=axis_index)
except TypeError:
new_data = np.flip(image.get_fdata(), axis=axis)
return new_img_like(image, data=new_data)
new_image = flip_image(nii_img, axis=[0])
affine = new_image.affine.copy()
hdr = new_image.header.copy()
new_data = new_image.get_fdata()
new_nii = nib.Nifti1Image(new_data, affine, hdr)
#the following is the part I have no idea how to write
New_NII_DIR = ('/Users/lena/test_new/001.nii')
nib.save(new_nii, New_NII_DIR)
[here is the example of my data, including 180 phases][1]
[1]: https://i.stack.imgur.com/wDh34.png
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.
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.
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 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.