How to disable anti-aliasing in QGIS export (pyqgis) - python-3.x

I'm trying to save a print layout as BMP in QGIS through python code, but want to turn of antialiasing and can't seem to figure out how to do it
def saveImage(self, layout, filename="defaultexport", extension=".bmp"):
"""Saves given layout as an image"""
filefolder = get_save_location()
filepath = os.path.join(filefolder, filename + extension)
if not os.path.isdir(filefolder):
os.makedirs(filefolder)
exporter = QgsLayoutExporter(layout)
context = QgsLayoutRenderContext(layout)
context.setFlag(context.FlagAntialiasing, False)
export_settings = exporter.ImageExportSettings()
export_settings.generateWorldFile = False
export_settings.dpi = 25
export_settings.flags = context.FlagAntialiasing
result = exporter.exportToImage(filepath, export_settings)
Is what I have. I have no idea what I'm doing with the QgsLayoutRenderContext, but it's about the only thing that seemed like it might do it. Saving manually and turning of the AA setting in save dialog works fine, but I need to do it through pyqgis

Revisting this project knowing some more Python and PyQt5 stuff this was an easy one
exporter = QgsLayoutExporter(layout)
context = QgsLayoutRenderContext(layout)
context.setFlag(context.FlagAntialiasing, False)
export_settings = exporter.ImageExportSettings()
export_settings.generateWorldFile = False
export_settings.dpi = 25
export_settings.flags = context.flags()
result = exporter.exportToImage(self.filepath, export_settings)
Needed to use context.flags()

Related

is there any way to switch ImageJ macro code to python3 code?

I'm making an app in python3 and I want to use some function in imagej. I used macro recorder to switch to python code but it got really messy, now I don't know how to do next. Can someone help me, please.
Here is the marco recorder code and my marco code
imp = IJ.openImage("D:/data/data_classify/data_train/1/9700TEST.6.tiff40737183_2.jpg");
//IJ.setTool("line");
//IJ.setTool("polyline");
xpoints = [177,155,114,101,100,159,179];
ypoints = [82,94,109,121,133,163,173];
imp.setRoi(new PolygonRoi(xpoints,ypoints,Roi.POLYLINE));
IJ.run(imp, "Straighten...", "title=9700TEST.6.tiff40737183_2-1.jpg line=30");
my python3 code
mport imagej
from scyjava import jimport
ij = imagej.init('2.5.0', mode='interactive')
print(ij.getVersion())
imp = ij.IJ.openImage("D:/data/data_classify/data_train/1/9700TEST.6.tiff40737183_2.jpg")
xpoints = [177,155,114,101,100,159,179]
xpoints_int = ij.py.to_java(xpoints)
ypoints = [82,94,109,121,133,163,173]
ypoints_int = ij.py.to_java(xpoints)
straightener = jimport('ij.plugin.Straightener')
polyRoi = jimport('ij.gui.PolygonRoi')
and I don't know how to do next...
After a few days, I finally found the answer. It is important to understand the parameters of the function to write, I have referenced in:
https://pyimagej.readthedocs.io/en/latest/
https://imagej.nih.gov/ij/developer/api/ij/module-summary.html
in my example the next thing i need is polygonroi from the given coordinates. I found the required coefficients of PolygonRoi in the above website and determined to take as parameters PolygonRoi​(int[] xPoints, int[] yPoints, int nPoints, int type)
Next, I found a way to convert my list of coordinates to an int[] which was shown in the pyimagej tutorial.
In the type section, I can find it by trying print(int(roi.PolygonRoi)) and the result is 6, you can also find the reason in the website above in the Roi section
The rest, the last thing you need to do is put that PolygonRoi into the Straightener function with the line value you want
Here is my code for using macro Imagej in Python3
import imagej
from scyjava import jimport
from jpype import JArray, JInt
ij = imagej.init('2.5.0', mode='interactive')
print(ij.getVersion())
imp = ij.IJ.openImage("D:/AI lab/joint_detection/data/1/9700TEST.6.tiff133328134_1.jpg")
xpoints = [124,126,131,137,131,128,121,114]
xpoints_int = JArray(JInt)(xpoints)
ypoints = [44,63,105,128,148,172,194,206]
ypoints_int = JArray(JInt)(ypoints)
straightener = jimport('ij.plugin.Straightener')
polyRoi = jimport('ij.gui.PolygonRoi')
roi = jimport('ij.gui.Roi')
new_polyRoi = polyRoi(xpoints_int,ypoints_int,len(xpoints), int(roi.POLYLINE))
imp.setRoi(new_polyRoi)
straightened_img = ij.IJ.run(imp, "Straighten...", "title=9700TEST.6.tiff40737183_2-1.jpg line=30")
ij.IJ.saveAs(straightened_img, 'Jpeg', './test.jpg')

How to fix unidentified character problem while passing data from TKinter to Photoshop via Python script?

I made a GUI Application which looks like this:
The ones marked red are Tkinter Text widgets and the ones marked yellow are Tkinter Entry widgets
After taking user input, the data is to be added to a PSD file and then rendered as an image. But Lets say, after taking the following data as input:
It renders the following Photoshop file:
How do I fix this issue that it does not recognize "\n" properly and hence the rendered document is rendered useless.
Here is the code which deals with converting of the accepted user data into strings and then adding it to Photoshop template and then rendering it:
def DataAdder2CSV():
global edate, eSNO, eage, egender, ename, ePID, econtact, ecomp, eallergy, ehistory, eR
e=edate.get()
a=eSNO.get()
d=eage.get()
f=egender.get()
b=ename.get()
c=ePID.get()
g=econtact.get()
h=ecomp.get(1.0,END)
i=eallergy.get(1.0,END)
j=ehistory.get(1.0,END)
k=eR.get(1.0,END)
data=[a,b,c,d,e,f,g,h,i,j,k]
file=open("Patient_Data.csv","a", newline="")
writer=csv.writer(file, delimiter=",")
writer.writerow(data)
file.close()
messagebox.showinfo("Prescription Generator", "Data has been saved to the database successfully!")
import win32com.client, os
objShell = win32com.client.Dispatch("WScript.Shell")
UserDocs = objShell.SpecialFolders("MyDocuments")
from tkinter import filedialog
ExpDir=filedialog.askdirectory(initialdir=UserDocs, title="Choose Destination Folder")
psApp = win32com.client.Dispatch("Photoshop.Application")
psApp.Open("D:\Coding\Python Scripts\Dr Nikhil Prescription App\Prescription Generator\Presc_Template.psd")
doc = psApp.Application.ActiveDocument
lf1 = doc.ArtLayers["name"]
tol1 = lf1.TextItem
tol1.contents = b
lf2 = doc.ArtLayers["age"]
tol2 = lf2.TextItem
tol2.contents = d
lf3 = doc.ArtLayers["gender"]
tol3 = lf3.TextItem
tol3.contents = f
lf4 = doc.ArtLayers["pid"]
tol4 = lf4.TextItem
tol4.contents = c
lf4 = doc.ArtLayers["date"]
tol4 = lf4.TextItem
tol4.contents = e
lf5 = doc.ArtLayers["contact"]
tol5 = lf5.TextItem
tol5.contents = g
lf6 = doc.ArtLayers["complaint"]
tol6 = lf6.TextItem
varH=" "+h.rstrip("\n")
tol6.contents =varH
lf7 = doc.ArtLayers["allergy"]
tol7 = lf7.TextItem
tol7.contents = i.rstrip("\n")
lf8 = doc.ArtLayers["history"]
tol8 = lf8.TextItem
varJ=" "+j.rstrip("\n")
tol8.contents =varJ
lf9 = doc.ArtLayers["R"]
tol9 = lf9.TextItem
tol9.contents = k.rstrip("\n")
options = win32com.client.Dispatch('Photoshop.ExportOptionsSaveForWeb')
options.Format = 13
options.PNG8 = False
pngfile =ExpDir+f"/{c}-{b}_({e}).png"
doc.Export(ExportIn=pngfile, ExportAs=2, Options=options)
messagebox.showinfo("Prescription Generator", "Prescription has been saved in the desired location successfully!")
There are 3 ways of expressing new line characters:
MacOS uses \r
Linux uses \n
Windows uses \r\n
Python and tkinter use \n but it looks like psApp.Application uses \r instead. That is why the document isn't rendered properly. For more info read the answers to this question.

How to write new input file after modify flopy package?

I try to load-if exists, update and write new input files in flopy. I try many things but I can't. Here is my code:
rchFile = os.path.join(modflowModel.model_ws, "hydrogeology.rch")
info = modflowModel.get_nrow_ncol_nlay_nper()
if "RCH" in modflowModel.get_package_list():
rchObject = ModflowRch.load(rchFile, modflowModel)
rchData = rchObject.rech
else:
rchData = dict()
for ts in range(info[3]):
rchData[ts] = np.zeros((info[0], info[1]))
for feat in iterator:
for ts in range(info[3]):
currValue = "random value"
rchData[ts][feat["row"]-1, feat["column"]-1] = currValue
rchObject = ModflowRch(modflowModel, nrchop=3, ipakcb=None, rech=rchData, irch=0, extension='rch', unitnumber=None, filenames="hydrogeology.rch")
rchPath = os.path.join(modflowModel.model_ws, 'rch.shp')
rchObject.export(f=rchPath)
# rchObject.write_file()
# modflowModel.add_package(rchObject)
modflowModel.write_input()
modflowModel is and flopy.modflow.Modflow object. Comments at the end of the codes are lines that I try to write updated new inputs but does not work.
What error(s) are you getting exactly when you say it doesnt work? I routinely modify forcing packages with flopy like this:
m = flopy.modflow.Modflow.load()
for kper in range(m.nper):
arr = m.rch.rech[kper].array
arr *= 0.8 # or something
m.rch.rech[kper] = arr
I found my error. modflowModel.write_input() works very well. Problem occures while loading model object Modflow.load(...). Now I load model whereever I need. Because if I load it another py etc., there might me model_ws confusion.

How to download a sentinel images from google earth engine using python API in tfrecord

While trying to download sentinel image for a specific location, the tif file is generated by default in drive but its not readable by openCV or PIL.Image().Below is the code for the same. If I use the file format as tfrecord. There are no Images downloaded in the drive.
starting_time = '2018-12-15'
delta = 15
L = -96.98
B = 28.78
R = -97.02
T = 28.74
cordinates = [L,B,R,T]
my_scale = 30
fname = 'sinton_texas_30'
llx = cordinates[0]
lly = cordinates[1]
urx = cordinates[2]
ury = cordinates[3]
geometry = [[llx,lly], [llx,ury], [urx,ury], [urx,lly]]
tstart = datetime.datetime.strptime(starting_time, '%Y-%m-%d') tend =
tstart+datetime.timedelta(days=delta)
collSent = ee.ImageCollection('COPERNICUS/S2').filterDate(str(tstart).split('')[0], str(tend).split(' ')[0]).filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20)).map(mask2clouds)
medianSent = ee.Image(collSent.reduce(ee.Reducer.median())) cropLand = ee.ImageCollection('USDA/NASS/CDL').filterDate('2017-01-01','2017-12-31').first()
task_config = {
'scale': my_scale,
'region': geometry,
'fileFormat':'TFRecord'
}
f1 = medianSent.select(['B1_median','B2_median','B3_median'])
taskSent = ee.batch.Export.image(f1,fname+"_Sent",task_config)
taskSent.start()
I expect the output to be readable in python so I can covert into numpy. In case of file format 'tfrecord', I expect the file to be downloaded in my drive.
I think you should think about the following things:
File format
If you want to open your file with PIL or OpenCV, and not with TensorFlow, you would rather use GeoTIFF. Try with this format and see if things are improved.
Saving to drive
Normally saving to your Drive is the default behavior. However, you can try to force writing to your drive:
ee.batch.Export.image.toDrive(image=f1, ...)
You can further try to setup a folder, where the images should be sent to:
ee.batch.Export.image.toDrive(image=f1, folder='foo', ...)
In addition, the Export data help page and this tutorial are good starting points for further research.

(Python/Pygame) Best way to load a LOT of images at the same time?

I have a function to load sounds, but not one for loading images. This is how my image loading is layed out currently:
if os.path.exists("themes/voltorb"):
vgui = pygame.image.load("themes/voltorb/gui.png")
voptions = pygame.image.load("themes/voltorb/options.png")
vachievements = pygame.image.load("themes/voltorb/achievements.png")
voverlay = pygame.image.load("themes/voltorb/overlay.png")
vconfirm = pygame.image.load("themes/voltorb/confirm.png")
vboom = pygame.mixer.Sound("themes/voltorb/boom.mp3")
vcoin = pygame.mixer.Sound("themes/voltorb/coin.mp3")
vtheme = {"gui":vgui,"options":voptions,"achievements":vachievements,"overlay":voverlay,"confirm":vconfirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"v":vtheme})
if os.path.exists("themes/fluttershy"):
fcoin = pygame.mixer.Sound("themes/fluttershy/coin.mp3")
fgui = pygame.image.load("themes/fluttershy/gui.png")
foptions = pygame.image.load("themes/fluttershy/options.png")
fachievements = pygame.image.load("themes/fluttershy/achievements.png")
foverlay = pygame.image.load("themes/fluttershy/overlay.png")
ftheme = {"gui":fgui,"options":foptions,"achievements":fachievements,"overlay":foverlay,"confirm":fconfirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"f":ftheme})
if os.path.exists("themes/mario"):
mgui = pygame.image.load("themes/mario/gui.png")
moptions = pygame.image.load("themes/mario/options.png")
machievements = pygame.image.load("themes/mario/achievements.png")
moverlay = pygame.image.load("themes/mario/overlay.png")
mtheme = {"gui":mgui,"options":moptions,"achievements":machievements,"overlay":moverlay,"confirm":mconfirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"m":mtheme})
if os.path.exists("%appdata%/KWScripts/Voltorb/themes/secret1"):
s1gui = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/gui.png")
s1options = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/options.png")
s1achievements = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/achievements.png")
s1overlay = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/overlay.png")
s1theme = {"gui":s1gui,"options":s1options,"achievements":s1achievements,"overlay":s1overlay,"confirm":s1confirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"s1":s1theme})
if os.path.exists("%appdata%/KWScripts/Voltorb/themes/secret2"):
s2gui = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/gui.png")
s2options = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/options.png")
s2achievements = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/achievements.png")
s2overlay = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/overlay.png")
s2theme = {"gui":s2gui,"options":s2options,"achievements":s2achievements,"overlay":s2overlay,"confirm":s2confirm,"coin":s2coin,"boom":s2boom,"music":s2music}
themedb.update({"s2":s2theme})
if os.path.exists("%appdata%/KWScripts/Voltorb/themes/secret3"):
s3gui = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/gui.png")
s3options = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/options.png")
s3achievements = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/achievements.png")
s3overlay = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/overlay.png")
s3theme = {"gui":s3gui,"options":s3options,"achievements":s3achievements,"overlay":s3overlay,"confirm":s3confirm,"coin":s3coin,"boom":s3boom,"music":s3music}
themedb.update({"s3":s3theme})
I'm not sure if there's any easy way to do this, but I have the most difficult way typed already. If anyone has an idea of how to shorten this, then thanks!
Take all your images and put them in a dict, where the key is the variable you were using, and the value is the path:
vimages = {'vgui': "themes/voltorb/gui.png", 'voptions': "themes/voltorb/options.png", 'vachievements': "themes/voltorb/achievements.png"} # and so on...
Then, iterate through vimages, checking for the existence of each individual file, then calling pygame.image.load() on it, and store the result in your already-existing dict (vtheme, in this case).
This way, you don't need to keep writing out pygame.image.load() over and over again.

Resources