Saving a multiple pdf file - reportlab - python-3.7

my code runs perfectly but the nested function (my_upd) does not run inside the report function. Only the function def (report): runs.
How can the nested function (my_upd) run together with the outer function (report) inside a class?.
What I want to achieve is when I click the "Report_But", the my_win window inside the report function should be displayed and when I select a date from the tkcalendar, my_upd function should run.
See the code bellow
from tkinter import *
class Main:
def __init__(self):
self.mainw = Tk()
self.mainw.title("Daily sales report")
width = 1000
height = 700
screen_width = self.mainw.winfo_screenwidth()
screen_height = self.mainw.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
self.mainw.geometry("%dx%d+%d+%d" % (width, height, x, y))
self.mainw.resizable(0, 0)
self.frame = Frame(self.mainw, width=1000, height=700, bg="#FFFFFF")
self.frame.place(x=0, y=0)
self.frameinfo = self.frame.place_info()
self.reportbut = Button(self.frame, text="Report_But", font="roboto 14", bd=5, width=8, bg="#FFFFFF",
command=self.report)
self.reportbut.place(x=10, y=5, height=40, width = 200)
def report(self):
import tkinter as tk
from tkinter import ttk
from tkcalendar import DateEntry
import sqlite3
self.my_win = tk.Tk()
self.my_win.geometry("1350x800") # Size of the window
self.my_win.title("Christ the light limitd") # Adding a title
self.sel = tk.StringVar()
self.cal = DateEntry(self.my_win, selectmode='day', textvariable=self.sel)
self.cal.grid(row=0, column=0, padx=20, pady=30)
def my_upd(*args):
if (len(self.sel.get()) > 4):
date = self.cal.get_date() # get selected date object from calendar
date1 = date.strftime('%y-%m-%d') # format for MySQL date column
date2 = date.strftime("%d-%B-%Y") # format to display at label
self.le1.config(text=date2) # display date at Label
conn = sqlite3.connect(r'E:\report.db')
c = conn.cursor()
query = ("select * from sales where Date = :d")
c.execute(query, (date1,))
saleslist = c.fetchall()
for item in self.trv.get_children(): # delete all previous listings
self.trv.delete(item)
total = 0 # to store total sale of the selected date
for data in saleslist:
self.trv.insert("", 'end', iid=data[0], text=data[0],
values=(data[0], data[1], data[2], data[3], data[4], data[5], data[6]))
total = round(total + (data[5]), 2)
self.le2.config(text="Total: " + str(total) + "ssp") # show total value
self.le1 = tk.Label(self.my_win, font=('Times', 22, 'bold'), fg='blue')
self.le1.grid(row=0, column=1)
self.trv = ttk.Treeview(self.my_win, selectmode='browse')
self.trv.grid(row=1, column=1, padx=20, pady=20)
# number of columns
self.trv["columns"] = ("1", "2", "3", "4", "5", "6", "7")
self.trv['height'] = 20
# Defining heading
self.trv['show'] = 'headings'
# width of columns and alignment
self.trv.column("1", width=100, anchor='c')
self.trv.column("2", width=100, anchor='c')
self.trv.column("3", width=100, anchor='c')
self.trv.column("4", width=100, anchor='c')
self.trv.column("5", width=100, anchor='c')
self.trv.column("6", width=100, anchor='c')
self.trv.column("7", width=100, anchor='c')
# respective columns
self.trv.heading("1", text="Transaction ID")
self.trv.heading("2", text="Invoice No.")
self.trv.heading("3", text="Product ID")
self.trv.heading("4", text="Description")
self.trv.heading("5", text="Quantity")
self.trv.heading("6", text="Total Price")
self.trv.heading("7", text="Date")
self.sel.trace('w', my_upd)
self.le2 = tk.Label(self.my_win, font=('Times', 22, 'bold'), fg='red')
self.le2.grid(row=1, column=2, sticky='ne', pady=20)
self.my_win.mainloop()
w=Main()
w.mainw.mainloop()

Related

Pillow new RGB screen not generating

I built a test program using import PIL.imagedraw etc etc and was able to use the draw.line command to draw various lines. All good. In a new program I added new code which built a matrix list of x/y/z points (and cosine/sine expressions with math.lib), an input command for some variables, and then the draw.line command as in the previous code, but now the RGB window is not showing at all. The program doesn’t end and gives no errors. (Pythonista on iOS iPad Pro)
The test program, a noob attempt at perspective projection (which works as expected):
import PIL.ImageDraw as ImageDraw,PIL.Image as Image, PIL.ImageShow as ImageShow
im = Image.new("RGB", (1200,800))
draw = ImageDraw.Draw(im)
GL_z = 0
PP_y = 0
SP_x = 300
SP_y = -400
SP_z = 600
org=600
answer=0
width=100
depth=500
height=500
SP_z1=SP_z+height
px_1 = org
py_1 = org
px_2 = org+90
py_2 = 50 + org
px_3 = -160 + org
py_3 = 550 + org
px_4 = -250 + org
py_4 = 500+org
while answer==0:
SP_z1=SP_z-height
px1_1 = ((px_1 - SP_x)/(py_1 - SP_y))*(py_1 - PP_y)
px1_2 = ((px_2 - SP_x)/(py_2 - SP_y))*(py_2 - PP_y)
px1_3 = ((px_3 - SP_x)/(py_3 - SP_y))*(py_3 - PP_y)
px1_4 = ((px_4 - SP_x)/(py_4 - SP_y))*(py_4 - PP_y)
py1_1 = ((SP_z-GL_z)/(py_1-SP_y))*(py_1-PP_y)
py1_2 = ((SP_z-GL_z)/(py_2-SP_y))*(py_2-PP_y)
py1_3 = ((SP_z-GL_z)/(py_3-SP_y))*(py_3-PP_y)
py1_4 = ((SP_z-GL_z)/(py_4-SP_y))*(py_4-PP_y)
py1_5 = ((SP_z1-GL_z)/(py_1-SP_y))*(py_1-PP_y)
py1_6 = ((SP_z1-GL_z)/(py_2-SP_y))*(py_2-PP_y)
py1_7 = ((SP_z1-GL_z)/(py_3-SP_y))*(py_3-PP_y)
py1_8 = ((SP_z1-GL_z)/(py_4-SP_y))*(py_4-PP_y)
px1_1old = px1_1
px1_2old = px1_2
px1_3old = px1_3
px1_4old = px1_4
py1_1old = py1_1
py1_2old = py1_2
py1_3old = py1_3
py1_4old = py1_4
py1_5old = py1_5
py1_6old = py1_6
py1_7old = py1_7
py1_8old = py1_8
SP_yold = SP_y
draw.line((0,SP_y,1200,SP_y),fill=(255,255,255))
draw.line((px1_1,py1_1,px1_2,py1_2),fill=(0,0,255))
draw.line((px1_2,py1_2,px1_3,py1_3),fill=(0,255,0))
draw.line((px1_3,py1_3,px1_4,py1_4),fill=(255,255,255))
draw.line((px1_4,py1_4,px1_1,py1_1),fill=(100,255,0))
draw.line((px1_1,py1_1,px1_1,py1_5),fill=(255,255,255))
draw.line((px1_1,py1_5,px1_2,py1_6),fill=(255,255,255))
draw.line((px1_2,py1_6,px1_3,py1_7),fill=(255,255,255))
draw.line((px1_3,py1_7,px1_4,py1_8),fill=(255,255,255))
draw.line((px1_4,py1_8,px1_4,py1_4),fill=(150,150,0))
#draw.line((px1_1,py1_1,px1_2,py1_2),fill=(255,255,255))
#draw.line((px1_2,py1_2,px1_3,py1_3),fill=(255,255,255))
#draw.line((px1_3,py1_3,px1_4,py1_4),fill=(255,255,255))
#draw.line((px1_4,py1_4,px1_1,py1_1),fill=(255,255,255))
im.show()
move = input("''")
if move == "w":
SP_y += 50
if move == "s":
SP_x -= 50
if move == "z":
SP_y -= 50
if move == "a":
SP_x += 50
if move == "-":
SP_z -= 50
if move == "=":
SP_z += 50
draw.line((0,SP_yold,1200,SP_yold),fill=(0,0,0))
draw.line((px1_1old,py1_1old,px1_2old,py1_2old),fill=(0,0,0))
draw.line((px1_2old,py1_2old,px1_3old,py1_3old),fill=(0,0,0))
draw.line((px1_3old,py1_3old,px1_4old,py1_4old),fill=(0,0,0))
draw.line((px1_4old,py1_4old,px1_1old,py1_1old),fill=(0,0,0))
draw.line((px1_1old,py1_1old,px1_1old,py1_5old),fill=(0,0,0))
draw.line((px1_1old,py1_5old,px1_2old,py1_6old),fill=(0,0,0))
draw.line((px1_2old,py1_6old,px1_3old,py1_7old),fill=(0,0,0))
draw.line((px1_3old,py1_7old,px1_4old,py1_8old),fill=(0,0,0))
draw.line((px1_4old,py1_8old,px1_4old,py1_4old),fill=(0,0,0))
And this is the code that refuses to draw anything:
import math
import decimal
decimal.getcontext().prec = 6
import PIL.ImageDraw as ImageDraw,PIL.Image as Image, PIL.ImageShow as ImageShow
im = Image.new("RGB", (1200,800))
draw = ImageDraw.Draw(im)
PP_y = 0
SP_x = 300
SP_y = -400
SP_z = 600
org=600
answer=0
dims=[]
for i in range (1, 5):
dim = int(input())
dims.append(dim)
dims[3] = (dims[3]*math.pi)/180
obj1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20,21],[22,23,24]]
y1 = [0,0,0,0,0,0,0,0]
y2 = [0,0,0,0,0,0,0,0]
y3 = [0,0,0,0,0,0,0,0]
x1 = [0,0,0,0,0,0,0,0]
z1 = [0,0,0,0,0,0,0,0]
ymod = [0,0,0,0,0,0,0,0]
xmod = [0,0,0,0,0,0,0,0]
obj1[0]=[0,0,0]
obj1[1]=[dims[0] * math.cos(dims[3]),dims[0] * math.sin(dims[3]),0]
obj1[2]=[obj1[1][0] - (dims[1] * math.sin(dims[3])),obj1[1][1] + (dims[1] * math.cos(dims[3])),0]
obj1[3]=[dims[1] * math.sin(dims[3]),dims[1] * math.cos(dims[3]),0]
obj1[4]=[0,0,dims[2]]
obj1[5]=[dims[0] * math.cos(dims[3]),dims[0] * math.sin(dims[3]),dims[2]]
obj1[6]=[obj1[1][0] - (dims[1] * math.sin(dims[3])),obj1[1][1] + (dims[1] * math.cos(dims[3])),dims[2]]
obj1[7]=[dims[1] * math.sin(dims[3]),dims[1] * math.cos(dims[3]),dims[2]]
for i in range (0,7):
y1[i]=obj1[i][1]-PP_y
y2[i]=obj1[i][1]-SP_y
y3[i]=y1[i]/y2[i]
x1[i]=obj1[i][0]-SP_y
z1[i]=obj1[i][2]-SP_z
obj1[i][0]=obj1[i][0] - (x1[i] * y3[i])
obj1[i][2]=obj1[i][2] - (z1[i] * y3[i])
#print(dims)
#print(obj1)
#print(y1,y2,y3,x1,z1,xmod,ymod)
while (True):
draw.line((obj1[0][0],obj1[0][2],obj1[1][0],obj1[1][2]),fill=(255,255,255))
Ah found the error, left out im.show(). Pretty fundamental…
reference
https://pillow.readthedocs.io/en/stable/reference/Image.html

Pine Script V5 - Not getting expected breakout entry price and entry in expected bar

I have a long entry buy condition where
Candle time frame is 15 minutes
Alert candle high is below lower band of bollinger bands.
entry when next candle crossover the alert candle high
This script gives entry oh high breakout + 0.01 but it does not give entry in the exact breakout candle and gives entry when price comes next time on expected entry price i.e. alert candle high + 0.01.
Requesting solution to get entry in breakout candle itself and at expected breakout price.
//#version=5
strategy("Bands Reversion", overlay=true, calc_on_every_tick=true)
//// Indicator Bollinger Bands
source = close
length = input.int(20, minval=1)
mult = input.float(1.5, minval=0.001, maxval=50)
direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev
plot(basis, color = color.red)
plot(upper)
plot(lower)
/// Trade entry time and squareoff time
TradeTime = input(title="Trade Timings",defval="0930-1130")
SqoffTime = input(title="Squareoff Timings",defval="1530-1545")
Barsinsession(TradeTime) => time(timeframe.period,TradeTime) != 0
Insession = Barsinsession(TradeTime) ? 1 : 0
endofsession = Insession == 0 and Insession[1] == 1
Sqsession = Barsinsession(SqoffTime) ? 1 : 0
SqTime = Sqsession == 1 and Sqsession[1] == 0
//// Input control and conditions
buy_condition = high[1] < lower[1] and ta.crossover(high, high[1]) and Insession
short_condition = low[1] > upper[1] and ta.crossunder(low, low[1]) and Insession
buy_alert_high = ta.valuewhen(buy_condition, high[1],0)
buy_alert_low = ta.valuewhen(buy_condition, low[1],0)
short_alert_low = ta.valuewhen(short_condition, low[1],0)
short_alert_high = ta.valuewhen(short_condition, high[1],0)
buy_alert_high1 = ta.valuewhen(buy_condition, high,0)
plot(buy_alert_high, style = plot.style_circles)
plot(buy_alert_low, style = plot.style_circles, offset = -2)
plot(short_alert_low, style = plot.style_circles)
plot(short_alert_high, style = plot.style_circles)
sell = ta.crossunder(close, low) or SqTime //// or SqTime if for intraday exit
cover = ta.crossover(close,high) or SqTime //// or SqTime if for intraday exit
plotshape(buy_condition, style = shape.triangleup, location = location.belowbar, color = color.green, text = "BUY")
plotshape(short_condition, style = shape.triangledown, location = location.abovebar, color = color.red, text = "SHORT")
long_price = ta.valuewhen(buy_condition, (buy_alert_high + 0.01),0 )
longstop = buy_alert_low - 0.01
longtgt = basis
short_price = ta.valuewhen(short_condition,short_alert_low - 0.01,0) ////short_alert_low - (0.01 * 100 * syminfo.mintick) //// ta.valuewhen(short_condition,short_alert_low - 0.01,0)
shortstop = short_alert_high + 0.01
shorttgt = basis
strategy.entry("long",direction = strategy.long, when = buy_condition, limit = long_price, comment ="BUY")
strategy.close("long", when = sell, comment = "SELL")
strategy.exit("long", from_entry = "long", stop = longstop, limit = longtgt, comment = "TG/SL_EXIT")
strategy.entry("short",direction = strategy.short, when = short_condition,limit = short_price, comment ="SHORT")
strategy.close("short", when = cover, comment = "COVER")
strategy.exit("short", from_entry = "short", stop = shortstop, limit = shorttgt, comment = "TG/SL_EXIT")
plot(strategy.position_size > 0 ? longstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size > 0 ? longtgt : na, style = plot.style_linebr, color = color.green)
plot(strategy.position_size < 0 ? shortstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size < 0 ? shorttgt : na, style = plot.style_linebr, color = color.green)

Condition only run ONCE (instead on all bars)

On checking for condition gap(high-low) > 0.1%(which is met multiple times), the label only gets
rendered ONCE (instead of on relevant bars within 25 bar lookback).
Plz provide a solution.
CODE :
Historical Bars
//#version=5
indicator("PriceMomemtum",overlay = true,max_bars_back = 25)
gap = (math.abs(high - low)/low ) * 100
//var gap = (math.abs(high - low)/low ) * 100
if gap > 0.1
var lbl = label.new(x = bar_index,y = na , text = na ,text_font_family = font.family_default ,xloc = xloc.bar_index,yloc =yloc.abovebar,style = label.style_arrowdown ,textcolor = color.white,size =size.small,textalign = text.align_left,tooltip = na)
label.set_text(lbl,str.tostring(gap,"#.00")+"%")
label.set_xy(lbl,bar_index,high )
Realtime Bars
//#version=5
indicator("PriceMomemtum",overlay = true,max_bars_back = 25)
if barstate.isrealtime
gap = (math.abs(high - low)/low ) * 100
//var gap = (math.abs(high - low)/low ) * 100
if gap > 0.1
var lbl = label.new(x = bar_index,y = na , text = na ,text_font_family = font.family_default ,xloc = xloc.bar_index,yloc =yloc.abovebar,style = label.style_arrowdown ,textcolor = color.white,size =size.small,textalign = text.align_left,tooltip = na)
label.set_text(lbl,str.tostring(gap,"#.00")+"%")
label.set_xy(lbl,bar_index,high )
alert(str.tostring(time(syminfo.timezone)) + "(PriceMomentum)", alert.freq_once_per_bar)
Have you tried defining "lbl" variable without "var"?
result

Plotting a series of numbers into horizontal lines

I've been trying to figure out the code to plot lines like these based on me copy and pasting a series of numbers into the code each day. I was trying to use an array but I'm not sure that's what I need to do. Any help would be greatly appreciated!
Example
//#version=5
indicator("Input Levels", overlay = true)
lev1 = input.float(3990, title = "Val 1", inline = "1")
col1 = input.color(color.black, title = "", inline = "1")
lev2 = input.float(3890, title = "Val 2", inline = "2")
col2 = input.color(color.green, title = "", inline = "2")
lev3 = input.float(3995, title = "Val 3", inline = "3")
col3 = input.color(color.black, title = "", inline = "3")
lev4 = input.float(3870, title = "Val 4", inline = "4")
col4 = input.color(color.red, title = "", inline = "4")
lev5 = input.float(3826, title = "Val 5", inline = "5")
col5 = input.color(color.black, title = "", inline = "5")
var float[] level_vals = array.from(lev1, lev2, lev3, lev4, lev5)
var color[] color_vals = array.from(col1, col2, col3, col4, col5)
var line[] level_lines = array.new_line()
size = array.size(level_vals)
if barstate.isfirst
for i = 0 to size - 1
array.push(level_lines, line.new(x1 = na, y1 = na, x2 = na, y2 = na, style = line.style_dashed, color = color.black, extend = extend.both))
if barstate.islast
for i = 0 to size - 1
line_i = array.get(level_lines, i)
val_i = array.get(level_vals, i)
color_i = array.get(color_vals, i)
line.set_xy1(line_i, x = bar_index - 1, y = val_i)
line.set_xy2(line_i, x = bar_index, y = val_i)
line.set_color(line_i, color = color_i)
You can save the numbers in an array, then run a for loop in the array and plot dashed line at them. Example below
//#version=5
indicator(title="Plot numbers")
var numbers=array.from(3992.5,3990.25,3989,3987.25,3985,3983.25,3981,3977.25,3971.25,3966.5)
if barstate.isfirst
for i = 0 to array.size(numbers) - 1
line.new(bar_index, array.get(numbers,i),bar_index, array.get(numbers,i), style = line.style_dashed, color = color.black, extend = extend.both)

Correcting satellite image overlays for Rayshader

I'm trying to improve the look of Rayshader by overlaying more recent (higher detail) satellite imagery (that I'm getting from the {leaflet} packages) but the overlay doesn't match with the 3D rendering.
Ideally I'm looking for a open-source solution that can get global satellite imagery. Bonus points if you find finer detail data for my area of interest - Hawaii.
One method using {geoviz} and {rayshader} uses the slippy_overlay() function to create a number of overlay images from either Mapbox (satellite, mapbox-streets-v8, mapbox-terrain-v2, mapbox-traffic-v1, terrain-rgb, mapbox-incidents-v1) or Stamen. Although I found mapbox-terrain-v2 the best it still lacks the detail I would like. Since it requires setting up an API for mapbox I just use stamen/watercolor below:
library(geoviz)
library(rayshader)
### Maui
lat = 20.785700
lon = -156.259204
square_km = 22
max_tiles = 10
dem <- mapzen_dem(lat, lon, square_km, max_tiles)
elev_matrix = matrix(
raster::extract(dem, raster::extent(dem), buffer=1000),
nrow = ncol(dem),
ncol = nrow(dem)
)
ambmat <- ambient_shade(elev_matrix, zscale = 30)
raymat <- ray_shade(elev_matrix, zscale = 30, lambert = TRUE)
watermap <- detect_water(elev_matrix)
overlay_img <-
slippy_overlay(dem,
image_source = "stamen",
image_type = "watercolor",
png_opacity = 0.3,
max_tiles = max_tiles)
elev_matrix %>%
sphere_shade(sunangle = 270, texture = "imhof4") %>%
add_water(detect_water(elev_matrix), color="imhof4") %>%
add_shadow(ray_shade(elev_matrix,zscale=3,maxsearch = 300),0.5) %>%
add_shadow(ambmat,0.5) %>%
add_overlay(overlay_img) %>%
plot_3d(elev_matrix,
solid = T,
water = T,
waterdepth = 0,
wateralpha = 0.5,
watercolor = "lightblue",
waterlinecolor = "white",
waterlinealpha = 0.5,
zscale= raster_zscale(dem) / 3,
fov=0,theta=135,zoom=0.75,phi=45, windowsize = c(1000,800))
I'm trying to adapt Will Bishop's workflow for getting overlays with the leaflet package but the result is very odd. Will's approach is a bit different as it fetches elevation data from USGS, which doesn't have baythmetric elevation which is must for me - so I used geoviz
library(leaflet)
# define bounding box with longitude/latitude coordinates
bbox <- list(
p1 = list(long = -156.8037, lat = 20.29737),
p2 = list(long = -155.7351, lat = 21.29577)
)
leaflet() %>%
addTiles() %>%
addRectangles(
lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
fillColor = "transparent"
) %>%
fitBounds(
lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
)
What's the area of my hillshade from geoviz?
dim(dem)
780 780 1
Okay so the overlay image needs to be 780 x 780 so I modify the helper functions to download the overlay with the World_Imagery base map:
define_image_size <- function(bbox, major_dim = 780) {
# calculate aspect ration (width/height) from lat/long bounding box
aspect_ratio <- abs((bbox$p1$long - bbox$p2$long) / (bbox$p1$lat - bbox$p2$lat))
# define dimensions
img_width <- ifelse(aspect_ratio > 1, major_dim, major_dim*aspect_ratio) %>% round()
img_height <- ifelse(aspect_ratio < 1, major_dim, major_dim/aspect_ratio) %>% round()
size_str <- paste(img_width, img_height, sep = ",")
list(height = img_height, width = img_width, size = size_str)
}
get_arcgis_map_image <- function(bbox, map_type = "World_Imagery", file = NULL,
width = 780, height = 780, sr_bbox = 4326) {
require(httr)
require(glue)
require(jsonlite)
url <- parse_url("https://utility.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task/execute")
# define JSON query parameter
web_map_param <- list(
baseMap = list(
baseMapLayers = list(
list(url = jsonlite::unbox(glue("https://services.arcgisonline.com/ArcGIS/rest/services/{map_type}/MapServer",
map_type = map_type)))
)
),
exportOptions = list(
outputSize = c(width, height)
),
mapOptions = list(
extent = list(
spatialReference = list(wkid = jsonlite::unbox(sr_bbox)),
xmax = jsonlite::unbox(max(bbox$p1$long, bbox$p2$long)),
xmin = jsonlite::unbox(min(bbox$p1$long, bbox$p2$long)),
ymax = jsonlite::unbox(max(bbox$p1$lat, bbox$p2$lat)),
ymin = jsonlite::unbox(min(bbox$p1$lat, bbox$p2$lat))
)
)
)
res <- GET(
url,
query = list(
f = "json",
Format = "PNG32",
Layout_Template = "MAP_ONLY",
Web_Map_as_JSON = jsonlite::toJSON(web_map_param))
)
if (status_code(res) == 200) {
body <- content(res, type = "application/json")
message(jsonlite::toJSON(body, auto_unbox = TRUE, pretty = TRUE))
if (is.null(file))
file <- tempfile("overlay_img", fileext = ".png")
img_res <- GET(body$results[[1]]$value$url)
img_bin <- content(img_res, "raw")
writeBin(img_bin, file)
message(paste("image saved to file:", file))
} else {
message(res)
}
invisible(file)
}
Now download the file, then load it
image_size <- define_image_size(bbox, major_dim = 780)
# fetch overlay image
overlay_file <- "maui_overlay.png"
get_arcgis_map_image(bbox, map_type = "World_Imagery", file = overlay_file,
# width = image_size$width, height = image_size$height,
sr_bbox = 4326)
overlay_img <- png::readPNG("maui_overlay.png")
Okay let's make the plot
elev_matrix %>%
sphere_shade(sunangle = 270, texture = "imhof4") %>%
add_water(detect_water(elev_matrix), color="imhof4") %>%
add_shadow(ray_shade(elev_matrix,zscale=3,maxsearch = 300),0.5) %>%
add_shadow(ambmat,0.5) %>%
add_overlay(overlay_img, alphacolor = 1) %>%
plot_3d(elev_matrix,
solid = T,
water = T,
waterdepth = 0,
wateralpha = 0.5,
watercolor = "lightblue",
waterlinecolor = "white",
waterlinealpha = 0.5,
zscale= raster_zscale(dem) / 3,
fov=0,theta=135,zoom=0.75,phi=45, windowsize = c(1000,800))
As you can see the overlay image is rotated to the hillshade.
Now I'm also realizing that fetching satellite with a bounding box method isn't ideal when you're trying to show bathymatrix data. It would be ideal to subset this overlay somehow programmatically but I'll probably just end up using inkscape once I've figured out how to rotate the overlay.
I tried to use the {magick}'s image_rotate() function to no avail:
library(magick)
maui <- magick::image_read("maui_overlay.png")
image_rotate(maui, 30) # -> maui_30
# image_write(maui_30, path = "maui_overlay_30.png", format = "png")
But magick has changed the dimensions:
# A tibble: 1 x 7
format width height colorspace matte filesize density
<chr> <int> <int> <chr> <lgl> <int> <chr>
1 PNG 1068 1068 sRGB TRUE 0 38x38
And will give an error with rayshader:
overlay_img <- png::readPNG("maui_overlay_30.png")
elev_matrix %>%
sphere_shade(sunangle = 270, texture = "imhof4") %>%
add_water(detect_water(elev_matrix), color="imhof4") %>%
add_shadow(ray_shade(elev_matrix,zscale=3,maxsearch = 300),0.5) %>%
add_shadow(ambmat,0.5) %>%
add_overlay(overlay_img, alphacolor = 1) %>%
plot_3d(elev_matrix,
solid = T,
water = T,
waterdepth = 0,
wateralpha = 0.5,
watercolor = "lightblue",
waterlinecolor = "white",
waterlinealpha = 0.5,
zscale= raster_zscale(dem) / 3,
fov=0,theta=135,zoom=0.75,phi=45, windowsize = c(1000,800))
Error in add_overlay(., overlay_img, alpha = 0.8) : argument 3 matches multiple formal arguments
The answer couldn't have been simpler... it needed to be transposed overlay_img = aperm(overlay_img, c(2,1,3)).