How to get real Landsat image conrers - python-3.x

How I can get actual coordinates of Landsat image corners (see image to understand) ?
From metadata file (..._MTL.txt) I can get coordinates of red corners, but I need to get coordinates of green corners.
I work with GeoTIFF files using GDAL.
I need to get correct latitude and longitude of green points.
Can I do it using python3?
Thanks for help
Metadata file
GROUP = L1_METADATA_FILE
GROUP = METADATA_FILE_INFO
ORIGIN = "Image courtesy of the U.S. Geological Survey"
REQUEST_ID = "9991103150002_00325"
PRODUCT_CREATION_TIME = 2011-03-16T20:14:24Z
STATION_ID = "EDC"
LANDSAT5_XBAND = "1"
GROUND_STATION = "IKR"
LPS_PROCESSOR_NUMBER = 0
DATEHOUR_CONTACT_PERIOD = "1016604"
SUBINTERVAL_NUMBER = "01"
END_GROUP = METADATA_FILE_INFO
GROUP = PRODUCT_METADATA
PRODUCT_TYPE = "L1T"
ELEVATION_SOURCE = "GLS2000"
PROCESSING_SOFTWARE = "LPGS_11.3.0"
EPHEMERIS_TYPE = "DEFINITIVE"
SPACECRAFT_ID = "Landsat5"
SENSOR_ID = "TM"
SENSOR_MODE = "BUMPER"
ACQUISITION_DATE = 2010-06-15
SCENE_CENTER_SCAN_TIME = 04:57:44.2830500Z
WRS_PATH = 145
STARTING_ROW = 26
ENDING_ROW = 26
BAND_COMBINATION = "1234567"
PRODUCT_UL_CORNER_LAT = 49.8314223
PRODUCT_UL_CORNER_LON = 84.0018859
PRODUCT_UR_CORNER_LAT = 49.8694055
PRODUCT_UR_CORNER_LON = 87.4313889
PRODUCT_LL_CORNER_LAT = 47.8261840
PRODUCT_LL_CORNER_LON = 84.1192898
PRODUCT_LR_CORNER_LAT = 47.8615913
PRODUCT_LR_CORNER_LON = 87.4144676
PRODUCT_UL_CORNER_MAPX = 284400.000
PRODUCT_UL_CORNER_MAPY = 5524200.000
PRODUCT_UR_CORNER_MAPX = 531000.000
PRODUCT_UR_CORNER_MAPY = 5524200.000
PRODUCT_LL_CORNER_MAPX = 284400.000
PRODUCT_LL_CORNER_MAPY = 5301000.000
PRODUCT_LR_CORNER_MAPX = 531000.000
PRODUCT_LR_CORNER_MAPY = 5301000.000
PRODUCT_SAMPLES_REF = 8221
PRODUCT_LINES_REF = 7441
PRODUCT_SAMPLES_THM = 4111
PRODUCT_LINES_THM = 3721
BAND1_FILE_NAME = "L5145026_02620100615_B10.TIF"
BAND2_FILE_NAME = "L5145026_02620100615_B20.TIF"
BAND3_FILE_NAME = "L5145026_02620100615_B30.TIF"
BAND4_FILE_NAME = "L5145026_02620100615_B40.TIF"
BAND5_FILE_NAME = "L5145026_02620100615_B50.TIF"
BAND6_FILE_NAME = "L5145026_02620100615_B60.TIF"
BAND7_FILE_NAME = "L5145026_02620100615_B70.TIF"
GCP_FILE_NAME = "L5145026_02620100615_GCP.txt"
METADATA_L1_FILE_NAME = "L5145026_02620100615_MTL.txt"
CPF_FILE_NAME = "L5CPF20100401_20100630_09"
END_GROUP = PRODUCT_METADATA
GROUP = MIN_MAX_RADIANCE
LMAX_BAND1 = 193.000
LMIN_BAND1 = -1.520
LMAX_BAND2 = 365.000
LMIN_BAND2 = -2.840
LMAX_BAND3 = 264.000
LMIN_BAND3 = -1.170
LMAX_BAND4 = 221.000
LMIN_BAND4 = -1.510
LMAX_BAND5 = 30.200
LMIN_BAND5 = -0.370
LMAX_BAND6 = 15.303
LMIN_BAND6 = 1.238
LMAX_BAND7 = 16.500
LMIN_BAND7 = -0.150
END_GROUP = MIN_MAX_RADIANCE
GROUP = MIN_MAX_PIXEL_VALUE
QCALMAX_BAND1 = 255.0
QCALMIN_BAND1 = 1.0
QCALMAX_BAND2 = 255.0
QCALMIN_BAND2 = 1.0
QCALMAX_BAND3 = 255.0
QCALMIN_BAND3 = 1.0
QCALMAX_BAND4 = 255.0
QCALMIN_BAND4 = 1.0
QCALMAX_BAND5 = 255.0
QCALMIN_BAND5 = 1.0
QCALMAX_BAND6 = 255.0
QCALMIN_BAND6 = 1.0
QCALMAX_BAND7 = 255.0
QCALMIN_BAND7 = 1.0
END_GROUP = MIN_MAX_PIXEL_VALUE
GROUP = PRODUCT_PARAMETERS
CORRECTION_METHOD_GAIN_BAND1 = "CPF"
CORRECTION_METHOD_GAIN_BAND2 = "CPF"
CORRECTION_METHOD_GAIN_BAND3 = "CPF"
CORRECTION_METHOD_GAIN_BAND4 = "CPF"
CORRECTION_METHOD_GAIN_BAND5 = "CPF"
CORRECTION_METHOD_GAIN_BAND6 = "IC"
CORRECTION_METHOD_GAIN_BAND7 = "CPF"
CORRECTION_METHOD_BIAS = "IC"
SUN_AZIMUTH = 141.2669762
SUN_ELEVATION = 59.9909680
OUTPUT_FORMAT = "GEOTIFF"
END_GROUP = PRODUCT_PARAMETERS
GROUP = CORRECTIONS_APPLIED
STRIPING_BAND1 = "NONE"
STRIPING_BAND2 = "NONE"
STRIPING_BAND3 = "NONE"
STRIPING_BAND4 = "NONE"
STRIPING_BAND5 = "NONE"
STRIPING_BAND6 = "NONE"
STRIPING_BAND7 = "NONE"
BANDING = "N"
COHERENT_NOISE = "N"
MEMORY_EFFECT = "Y"
SCAN_CORRELATED_SHIFT = "Y"
INOPERABLE_DETECTORS = "N"
DROPPED_LINES = "N"
END_GROUP = CORRECTIONS_APPLIED
GROUP = PROJECTION_PARAMETERS
REFERENCE_DATUM = "WGS84"
REFERENCE_ELLIPSOID = "WGS84"
GRID_CELL_SIZE_THM = 60.000
GRID_CELL_SIZE_REF = 30.000
ORIENTATION = "NUP"
RESAMPLING_OPTION = "CC"
MAP_PROJECTION = "UTM"
END_GROUP = PROJECTION_PARAMETERS
GROUP = UTM_PARAMETERS
ZONE_NUMBER = 45
END_GROUP = UTM_PARAMETERS
END_GROUP = L1_METADATA_FILE
END

You might first find the contour with the biggest area. Then try some algorithm to find the points you want. It seems that the satellite picture in the image is not a perfect rectangle, so you can't fit a rectangle on it using OpenCV's built-in methods.
You should try something like that:
import cv2
import numpy as np
img = cv2.imread('z_edited.jpg')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(imgray, (11, 11), 0)
ret, thresh = cv2.threshold(blurred, 27, 255, 0)
cnts, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area = 0
max_area_index = 0
for i, cnt in enumerate(cnts):
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
max_area_index = i
x_min = np.min(cnts[max_area_index][:, 0, 0])
x_max = np.max(cnts[max_area_index][:, 0, 0])
y_min = np.min(cnts[max_area_index][:, 0, 1])
y_max = np.max(cnts[max_area_index][:, 0, 1])
(x_left, y_left) = (x_min, cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 0] == x_min)), 0, 1])
(x_right, y_right) = (x_max, cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 0] == x_max)), 0, 1])
(x_down, y_down) = (cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 1] == y_max)), 0, 0], y_max)
(x_top, y_top) = (cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 1] == y_min)), 0, 0], y_min)
cv2.circle(img, (x_left, y_left), 10, (0, 0, 255), thickness=8)
cv2.circle(img, (x_right, y_right), 10, (0, 0, 255), thickness=8)
cv2.circle(img, (x_down, y_down), 10, (0, 0, 255), thickness=8)
cv2.circle(img, (x_top, y_top), 10, (0, 0, 255), thickness=8)
# cv2.drawContours(img, cnts, max_area_index, (0, 255, 0), 2)
cv2.namedWindow('s', cv2.WINDOW_NORMAL)
cv2.imshow('s', img)
cv2.waitKey(0)
And the result looks like:
Using this code you can find the coordinates of the corners of the satellite picture inside the image(red points).
Also need to say I have assumed that your satellite picture background is completely black(the image you have uploaded, has a thin gray strip around the whole image).

Related

How to change color of mark on topoplot interactively?

I want to create interactive line- and topoplot depending on menu. I figured out how to make red the line chosen in menu, but it doesn't work for topoplot marks (black circles inside topoplot). I can change it manually (cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)), but how to do that interactively?
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
ax = Axis(f[1:3, 1], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
N = 1:length(pos) #1:4
hidespines!(ax, :t, :r)
GLMakie.xlims!(-0.3, 1.2)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
times = range(-0.3, length=size(dat_e,2), step=1 ./ 128)
lines = Dict()
for i in N
mean_trial = mean(dat_e[i,:,:],dims=2)[:,1]
line = lines!(times, mean_trial, color = "black")
lines[i] = line
end
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
topo_axis = Axis(f[2, 2], width = 178, height = 178, aspect = DataAspect())
Makie.xlims!(low = -0.2, high = 1.2)
Makie.ylims!(low = -0.2, high = 1.2)
topoMatrix = eegHeadMatrix(pos[N], (0.5, 0.5), 0.5)
cmap = Observable(collect(ColorScheme(range(colorant"black", colorant"black", length=30))))
#cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)
topo = eeg_topoplot!(topo_axis, N, # averaging all trial of 30 participants on Xth msec
raw.ch_names[1:30];
positions=pos, # produced automatically from ch_names
interpolation=NullInterpolator(),
enlarge=1,
#colorrange = (0, 1), # add the 0 for the white-first color
colormap = cmap[],
label_text=false)
hidedecorations!(current_axis())
hidespines!(current_axis())
num_prev = 0
menu = Menu(f[3, 2], options = raw.ch_names[1:30], default = nothing)#, default = "second")
on(menu.selection) do selected
if selected != nothing
num = findall(x->x==menu.selection[], raw.ch_names[1:30])[]
if num_prev != 0
lines[num_prev].color = "black"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
end
lines[num].color = "red"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
num_prev = num
end
end
notify(menu.selection)
#print(cmap[])
f
We solved this by putting this string at the end of the menu.selection section:
notify(lines)
It works, because lines() automatically creates Observable.

Why am i not getting any visualisation Vpython?

I am trying to simulate some planets and their moons around the sun but not getting scene opened up.`from vpython import*
def open_scene(breedte, hoogte):
global open_venster
c = canvas(width=breedte, height=hoogte, background=color.black)
c.center = vector(0,0,0)
c.range = breedte
c.autozoom = True
c.autoscale = False
c.userzoom = True
c.userspin = False
c.userpan = False
return c
open_scene(400, 400)
def solarsystem(n, dt):
He = planets_from_file("planeten.txt")
planets = []
sun = sphere(pos = vector(0,0,0), radius = He[0].straal_v_hemellichaam, color = kleuromzetting(He[0].kleur))
earth = sphere(pos = vector(-He[3].straal_vd_baan, 0, 0), radius= He[3].straal_v_hemellichaam*50, texture= textures.earth)
moon = sphere(pos = vector(-He[4].straal_vd_baan,0,0), radius = He[4].straal_v_hemellichaam, color = kleuromzetting(He[4].kleur))
mercurius = sphere(pos = vector(-He[1].straal_vd_baan,0,0), radius = He[1].straal_v_hemellichaam, color = kleuromzetting(He[1].kleur))
venus = sphere(pos = vector(-He[2].straal_vd_baan,0,0), radius = He[2].straal_v_hemellichaam, color = kleuromzetting(He[2].kleur))
mars = sphere(pos = vector(-He[5].straal_vd_baan,0,0), radius = He[5].straal_v_hemellichaam, color = kleuromzetting(He[5].kleur))
phobos = sphere(pos = vector(-He[6].straal_vd_baan-He[5].straal_vd_baan,0,0), radius = He[6].straal_v_hemellichaam, color = kleuromzetting(He[6].kleur))
deimos = sphere(pos = vector(-He[7].straal_vd_baan-He[5].straal_vd_baan,0,0), radius = He[7].straal_v_hemellichaam, color = kleuromzetting(He[7].kleur))
jupiter = sphere(pos = vector(-He[8].straal_vd_baan,0,0), radius = He[8].straal_v_hemellichaam, color = kleuromzetting(He[8].kleur))
io = sphere(pos = vector(-He[9].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[9].straal_v_hemellichaam, color = kleuromzetting(He[9].kleur))
europa = sphere(pos = vector(-He[10].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[10].straal_v_hemellichaam, color = kleuromzetting(He[10].kleur))
ganymede = sphere(pos = vector(-He[11].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[11].straal_v_hemellichaam, color = kleuromzetting(He[11].kleur))
callisto = sphere(pos = vector(-He[12].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[12].straal_v_hemellichaam, color = kleuromzetting(He[12].kleur))
sun.velocity = vector(0, 0, 0)
earth.velocity = He[3].snelheid
moon.velocity = He[4].snelheid
mercury.velocity = He[1].snelheid
venus.velocity = He[2].snelheid
mars.velocity =He[5].snelheid
phobos.velocity = He[6].snelheid
deimos.velocity = He[7].snelheid
jupiter.velocity = He[8].snelheid
io.velocity = He[9].snelheid
europa.velocity = He[10].snelheid
ganymede.velocity = He[11].snelheid
callisto.velocity = He[12].snelheid
sun.massa = He[0].massa
earth.massa = He[3].massa
moon.massa = He[4].massa
mercury.massa = He[1].massa
venus.massa = He[2].massa
mars.massa =He[5].massa
phobos.massa = He[6].massa
deimos.massa = He[7].massa
jupiter.massa = He[8].massa
io.massa = He[9].massa
europa.massa = He[10].massa
ganymede.massa = He[11].massa
callisto.massa = He[12].massa
planets.extend((sun, earth, moon, mercurius, venus, mars, phobos, jupiter, io, europa, ganymede, calisto))
while True:
sleep(0.02)
for planet in planets:
a = calc_gravitational_acceleration(planet.massa, planet.pos)
planet.velocity -= a*dt
planet.pos += planet.velocity * dt`

tkinter sliders are stuck together

I'm having trouble separating these 2 sliders. They seem to be tracking together, but the variables seem to no be unique, and I can't figure out why. Can anyone help?
import tkinter as tk
sBoard = tk.Tk()
sBoard.geometry("800x400")
ch1_Frame = tk.LabelFrame(sBoard, text = "CH 1", bd = 5)
ch1_val = 0
ch1 = tk.Scale(ch1_Frame, variable = ch1_val, from_ =100, to = 0, showvalue = 0, width = 25, length = 200)
ch1.pack()
button1 = tk.Button(ch1_Frame, text = "Power")
button1.pack()
ch1_Frame.place(x=25, y=50)
ch2_Frame = tk.LabelFrame(sBoard, text = "CH 2", bd = 5)
ch2_val = 0
ch2 = tk.Scale(ch2_Frame, variable = ch2_val, from_ =100, to = 0, showvalue = 0, width = 25, length = 200)
ch2.pack()
button2 = tk.Button(ch2_Frame, text = "Power")
button2.pack()
ch2_Frame.place(x=150, y=50)
sBoard.mainloop()
The variable must be one of the tkinter variable types, for example an IntVar:
ch1_val = tk.IntVar()
ch1 = tk.Scale(ch1_Frame, variable = ch1_val, from_ =100, to = 0, showvalue = 0, width = 25, length = 200)
ch1.pack()

My residual neural network is giving a very strange depth map as output .I dont know how to improve my model?

The output i am getting from my residual model is an image with small little squares on it ( a very low resolution image), but it is supposed to give me a depth map. The objects in the image are lost and only those small squares are visible. I don't how to improvise it ?
def mini_model(input_shape) :
# Define the input as a tensor with shape input_shape
X_input = Input(input_shape)
# Zero_Padding
X = ZeroPadding2D((3,3))(X_input)
#stage_1
X = Conv2D(64,(7,7),strides = (2,2),name = 'conv1')(X)
X = BatchNormalization(axis = 3,name = 'bn_conv1')(X)
X = Activation('relu')(X)
X = MaxPooling2D((3,3),strides = (2,2))(X)
# Stage 2
X = convolutional_block(X, f = 3, filters = [64, 64, 256], stage = 2, block='a', s = 1)
X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')
X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')
#stage3
X = convolutional_block(X,f = 3 , filters = [128,128,512],stage = 3,block = 'a', s = 2)
X = identity_block(X,3,[128,128,512],stage = 3,block='b')
X = identity_block(X,3,[128,128,512],stage = 3 , block = 'c')
X = identity_block(X,3,[128,128,512],stage = 3 , block = 'd')
#stage 4
X = convolutional_block(X,f = 3 , filters = [256,256,1024],stage = 4,block = 'a', s = 2)
X = identity_block(X,3,[256,256,1024],stage = 4,block='b')
X = identity_block(X,3,[256,256,1024],stage = 4,block='c')
X = identity_block(X,3,[256,256,1024],stage = 4,block='d')
X = identity_block(X,3,[256,256,1024],stage = 4,block='e')
X = identity_block(X,3,[256,256,1024],stage = 4,block='f')
X = identity_block(X,3,[256,256,1024],stage = 4,block='g')
X = identity_block(X,3,[256,256,1024],stage = 4,block='h')
X = identity_block(X,3,[256,256,1024],stage = 4,block='i')
X = identity_block(X,3,[256,256,1024],stage = 4,block='j')
X = identity_block(X,3,[256,256,1024],stage = 4,block='k')
X = identity_block(X,3,[256,256,1024],stage = 4,block='l')
#stage 5
X = convolutional_block(X,f = 3 , filters = [512,512,2048],stage = 5,block = 'a', s = 2)
X = identity_block(X,3,[512,512,2048],stage = 5,block='b')
X = identity_block(X,3,[512,512,2048],stage = 5,block='c')
# AVGPOOL
X = Conv2D(3,kernel_size=(3,3), padding = 'same',use_bias = False)(X)
X = UpSampling2D(size=2)(X)
X = UpSampling2D(size=2)(X)
X = UpSampling2D(size=2)(X)
X = UpSampling2D(size=2)(X)
X = UpSampling2D(size=2)(X)
# Create model
model = Model(inputs = X_input, outputs = X)
return(model)
my residual model!!
input image shape = (480,640,3)
Actual results : The image is made of small squares , with different levels of gray.
Expected results : The image should be an depth map of the same size as input (480,640,3)
You have five upsampling layers in sequence. That's exactly what is expected from that. Big squares of 32 pixels. (2^5 = 32)
You should probably read about U-nets, create more convolutions between the upsamplings and connections from the resnet to the upsampling results.

Display multiple images in PIL

-------------------------------Solved(Partially)----------------------------------------
My problem is that when I try to display multiple images on the canvas using PIL, I end up with only the last image.
All the images have slightly different characteristics(angle offset). Also the having a plethora of entries, I have to use a loop for sure. Also I'll need to use PIL(tkinter objects not possible) for the angle offset feature.
Here is the code;
#!/usr/bin/python
# Filename: weather_sim.py
import os
import tkinter as tk
import h5py as hp
import numpy as np
import ntpath as ntp
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename
def path_leaf(path):
head, tail = ntp.split(path)
return tail or ntp.basename(head)
class CoordFind:
def __init__(self):
self.LatPx = 0
self.LonPx = 0
def find_px(self, Lat, Lon):
self.LatPx = (Lat - LatN)/LatLc
self.LonPx = (Lon - LonW)/LonLc
class PlottingGUI(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.coord = CoordFind()
self.root = parent
self.root.wm_title("-|-|-|-|||Wind Vector Plotter|||-|-|-|-")
self.root.resizable(False, False)
self.path = "None Selected"
self.HaM = 0
self.Lat = 0
self.Lon = 0
self.WiD = 0
self.WiS = 0
self.fr = tk.Frame(self.root, width = (width+20), height = (height+20), bd = 2)
self.fr.grid(row = 1, column = 0)
self.frBro = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frBro.grid(row = 0, column = 0)
self.frHi = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frHi.grid(row = 2, column = 0)
self.cv = tk.Canvas(self.fr, width = width, height = height, background = "white", bd = 0, relief = tk.SUNKEN)
self.cv.grid(row = 0, column = 0)
self.cv.create_image(1, 1, anchor = "nw", image = photo)
self.broButton = tk.Button(self.frBro, text = "Browse Dsets", command = self.analyseDset, height = 3, width = 16, bg = "yellow")
self.broButton.grid(row = 0, column = 0, padx = 20)
self.selFile = tk.Label(self.frBro, text = self.path)
self.selFile.grid(row = 0, column = 1)
self.caution = tk.Label(self.frHi, text = "Optional use. Warning!!, May lead to lags in program", fg = "red")
self.caution.grid(row = 0, column = 1)
self.shoRedBut = tk.Button(self.frHi, text = "Show H1", command = self.show_barbs1().__next__, height = 3, width = 16, bg = "#FF0000", fg = "white", activebackground="#E533B5")
self.shoRedBut.grid(row = 1, column = 0, padx = 7, pady = 2)
self.shoGrnBut = tk.Button(self.frHi, text = "Show H2", command = self.show_barbs2().__next__, height = 3, width = 16, bg = "#00B400", fg = "white", activebackground="#B5E533")
self.shoGrnBut.grid(row = 1, column = 1, padx = 7, pady = 2)
self.shoBluBut = tk.Button(self.frHi, text = "Show H3", command = self.show_barbs3().__next__, height = 3, width = 16, bg = "#0000FF", fg = "white", activebackground="#33B5E5")
self.shoBluBut.grid(row = 1, column = 2, padx = 7, pady = 2)
self.desc1 = tk.Label(self.frHi, text = "100-250 hPa", fg = "white", bg = "black")
self.desc1.grid(row = 2, column = 0)
self.desc2 = tk.Label(self.frHi, text = "250-350 hPa", fg = "white", bg = "black")
self.desc2.grid(row = 2, column = 1)
self.desc3 = tk.Label(self.frHi, text = "350-700 hPa", fg = "white", bg = "black")
self.desc3.grid(row = 2, column = 2)
def analyseDset(self):
self.path = askopenfilename(filetypes = (("Dataset files", "*.h5")
,("All files", "*.*") ))
self.jfname = path_leaf(self.path)
self.selFile = tk.Label(self.frBro, text = self.jfname)
self.selFile.grid(row = 0, column = 1)
self.extDset()
def extDset(self):
hf = hp.File(self.path, 'r')
HaM = hf.get('HEIGHT_ASSIGNMENT_METHOD')
Lat = hf.get('Latitude')
Lon = hf.get('Longitude')
WiD = hf.get('WIND_DIRECTION')
WiS = hf.get('WIND_SPEED')
self.HaM = np.array(HaM)
self.Lat = np.array(Lat)/100
self.Lon = np.array(Lon)/100
self.WiD = np.array(WiD)
self.WiS = np.array(WiS)
self.BrbImR = np.empty((self.HaM.shape[0],1))
self.BrbImB = np.empty((self.HaM.shape[0],1))
def show_barbs1(self):
self.coord = CoordFind()
script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Red_Barbs\icons8-wind-speed-43-47-50.png'))
w, h = im.size
im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im = ImageTk.PhotoImage(im.rotate(45))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 0:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImR[i] = self.cv.create_image(x, y, image = vec_im)
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImR[i], state = tk.NORMAL)
self.shoRedBut.configure(text = "Showing H1")
yield
def show_barbs2(self):
self.coord = CoordFind()
BrbImG = np.empty((self.HaM.shape[0],1))
script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Green_Barbs\icons8-wind-speed-43-47-50.png'))
w, h = im.size
im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 1:
vec_im = ImageTk.PhotoImage(im.rotate(self.WiD[i]))
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
BrbImG[i] = self.cv.create_image(x, y, image = vec_im)
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(BrbImG[i], state = tk.NORMAL)
self.shoGrnBut.configure(text = "Showing H2")
yield
def show_barbs3(self):
self.coord = CoordFind()
script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Blue_Barbs\icons8-wind-speed-43-47-50.png'))
w, h = im.size
im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im = ImageTk.PhotoImage(im.rotate(180))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 2:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImB[i] = self.cv.create_image(x, y, image = vec_im)
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImB[i], state = tk.NORMAL)
self.shoBluBut.configure(text = "Showing H3")
yield
if __name__ == "__main__":
root = tk.Tk()
backmap = "Map.png"
photo = ImageTk.PhotoImage(file = backmap)
width = photo.width()
height = photo.height()
LatN = 69.5
LatS = -69.3
LonE = 148.9
LonW = 1.0
LatLc = (LatS - LatN)/height
LonLc = (LonE - LonW)/width
app = PlottingGUI(root)
root.mainloop()
The output currently is this;(For the green arrows as that is what I have tested on)
This is what I want;(But with different angles)
I am using Python 3.6 on Windows 10.
Thanks in advance!!
P.S.: Also there is another problem if someone can help me with that. I would like to be able to choose a particular image based on a range factor(Wind Speed) by doing like a switch-case(or if-elif-else) procedure if possible. But when I try to do that it says "No such File or Directory". I may put it in another Question though.
-------------------------------Solved(Till this point)---------------------------------
EDIT: Solved the problem of displaying multiple arrows according to
choice and at different angles.
Here's the code;
#!/usr/bin/python
# Filename: weather_sim.py
import os
import tkinter as tk
import h5py as hp
import numpy as np
import ntpath as ntp
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename
def path_leaf(path):
head, tail = ntp.split(path)
return tail or ntp.basename(head)
class CoordFind:
def __init__(self):
self.LatPx = 0
self.LonPx = 0
def find_px(self, Lat, Lon):
self.LatPx = (Lat - LatN)/LatLc
self.LonPx = (Lon - LonW)/LonLc
class PlottingGUI(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.coord = CoordFind()
self.root = parent
self.root.wm_title("-|-|-|-|||Wind Vector Plotter|||-|-|-|-")
self.root.resizable(False, False)
self.path = "None Selected"
self.HaM = 0
self.Lat = 0
self.Lon = 0
self.WiD = 0
self.WiS = 0
self.ima = []
self.fr = tk.Frame(self.root, width = (width+20), height = (height+20), bd = 2)
self.fr.grid(row = 1, column = 0)
self.frBro = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frBro.grid(row = 0, column = 0)
self.frHi = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frHi.grid(row = 2, column = 0)
self.cv = tk.Canvas(self.fr, width = width, height = height, background = "white", bd = 0, relief = tk.SUNKEN)
self.cv.grid(row = 0, column = 0)
self.cv.create_image(1, 1, anchor = "nw", image = photo)
self.broButton = tk.Button(self.frBro, text = "Browse Dsets", command = self.analyseDset, height = 3, width = 16, bg = "yellow")
self.broButton.grid(row = 0, column = 0, padx = 20)
self.selFile = tk.Label(self.frBro, text = self.path)
self.selFile.grid(row = 0, column = 1)
self.caution = tk.Label(self.frHi, text = "Optional use. Warning!!, May lead to lags in program", fg = "red")
self.caution.grid(row = 0, column = 1)
self.shoRedBut = tk.Button(self.frHi, text = "Show H1", command = self.show_barbs1().__next__, height = 3, width = 16, bg = "#FF0000", fg = "white", activebackground="#E533B5")
self.shoRedBut.grid(row = 1, column = 0, padx = 7, pady = 2)
self.shoGrnBut = tk.Button(self.frHi, text = "Show H2", command = self.show_barbs2().__next__, height = 3, width = 16, bg = "#00B400", fg = "white", activebackground="#B5E533")
self.shoGrnBut.grid(row = 1, column = 1, padx = 7, pady = 2)
self.shoBluBut = tk.Button(self.frHi, text = "Show H3", command = self.show_barbs3().__next__, height = 3, width = 16, bg = "#0000FF", fg = "white", activebackground="#33B5E5")
self.shoBluBut.grid(row = 1, column = 2, padx = 7, pady = 2)
self.desc1 = tk.Label(self.frHi, text = "100-250 hPa", fg = "white", bg = "black")
self.desc1.grid(row = 2, column = 0)
self.desc2 = tk.Label(self.frHi, text = "250-350 hPa", fg = "white", bg = "black")
self.desc2.grid(row = 2, column = 1)
self.desc3 = tk.Label(self.frHi, text = "350-700 hPa", fg = "white", bg = "black")
self.desc3.grid(row = 2, column = 2)
def analyseDset(self):
self.path = askopenfilename(filetypes = (("Dataset files", "*.h5")
,("All files", "*.*") ))
self.jfname = path_leaf(self.path)
self.selFile = tk.Label(self.frBro, text = self.jfname)
self.selFile.grid(row = 0, column = 1)
self.extDset()
def extDset(self):
hf = hp.File(self.path, 'r')
HaM = hf.get('HEIGHT_ASSIGNMENT_METHOD')
Lat = hf.get('Latitude')
Lon = hf.get('Longitude')
WiD = hf.get('WIND_DIRECTION')
WiS = hf.get('WIND_SPEED')
self.HaM = np.array(HaM)
self.Lat = np.array(Lat)/100
self.Lon = np.array(Lon)/100
self.WiD = np.array(WiD)
self.WiS = np.array(WiS)
self.BrbImR = np.empty((self.HaM.shape[0],1))
self.BrbImG = np.empty((self.HaM.shape[0],1))
self.BrbImB = np.empty((self.HaM.shape[0],1))
def barb_def(self, WiS):
if WiS < 1:
self.ima = "1.png"
elif WiS < 3:
self.ima = "2.png"
elif WiS < 8:
self.ima = "3.png"
elif WiS < 13:
self.ima = "4.png"
elif WiS < 18:
self.ima = "5.png"
elif WiS < 23:
self.ima = "6.png"
elif WiS < 28:
self.ima = "7.png"
elif WiS < 33:
self.ima = "8.png"
elif WiS < 38:
self.ima = "9.png"
elif WiS < 43:
self.ima = "10.png"
elif WiS < 48:
self.ima = "11.png"
elif WiS < 53:
self.ima = "12.png"
elif WiS < 58:
self.ima = "13.png"
elif WiS < 63:
self.ima = "14.png"
elif WiS < 68:
self.ima = "15.png"
elif WiS < 73:
self.ima = "16.png"
elif WiS < 78:
self.ima = "17.png"
elif WiS < 83:
self.ima = "18.png"
elif WiS < 88:
self.ima = "19.png"
elif WiS < 93:
self.ima = "20.png"
elif WiS < 98:
self.ima = "21.png"
elif WiS < 103:
self.ima = "22.png"
else:
self.ima = "23.png"
def show_barbs1(self):
self.coord = CoordFind()
vec_im = []
im = []
p = []
script_dir = os.path.dirname(os.path.abspath(__file__))
for i in range(0, self.HaM.shape[0]):
self.barb_def(self.WiS[i])
p.append("{}{}".format('Red_Barbs\\', self.ima))
im.append(Image.open(os.path.join(script_dir, p[i])))
w, h = im[i].size
im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i])))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 0:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImR[i] = self.cv.create_image(x, y, image = vec_im[i])
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImR[i], state = tk.NORMAL)
self.shoRedBut.configure(text = "Showing H1")
yield
def show_barbs2(self):
self.coord = CoordFind()
vec_im = []
im = []
p = []
script_dir = os.path.dirname(os.path.abspath(__file__))
for i in range(0, self.HaM.shape[0]):
self.barb_def(self.WiS[i])
p.append("{}{}".format('Green_Barbs\\', self.ima))
im.append(Image.open(os.path.join(script_dir, p[i])))
w, h = im[i].size
im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i])))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 1:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImG[i] = self.cv.create_image(x, y, image = vec_im[i])
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImG[i], state = tk.NORMAL)
self.shoGrnBut.configure(text = "Showing H2")
yield
def show_barbs3(self):
self.coord = CoordFind()
vec_im = []
im = []
p = []
script_dir = os.path.dirname(os.path.abspath(__file__))
for i in range(0, self.HaM.shape[0]):
self.barb_def(self.WiS[i])
p.append("{}{}".format('Blue_Barbs\\', self.ima))
im.append(Image.open(os.path.join(script_dir, p[i])))
w, h = im[i].size
im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i])))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 2:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImB[i] = self.cv.create_image(x, y, image = vec_im[i])
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImB[i], state = tk.NORMAL)
self.shoBluBut.configure(text = "Showing H3")
yield
if __name__ == "__main__":
root = tk.Tk()
backmap = "Map.png"
photo = ImageTk.PhotoImage(file = backmap)
width = photo.width()
height = photo.height()
LatN = 69.5
LatS = -69.3
LonE = 148.9
LonW = 1.0
LatLc = (LatS - LatN)/height
LonLc = (LonE - LonW)/width
app = PlottingGUI(root)
root.mainloop()
But this ended up having a new problem. One set of coloured arrows is showing at a time but when I click the button to display another set it goes "Python stopped working because of some error" and then the shell restarts. Don't know what's the prob though.

Resources