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')
Related
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.
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()
I am using pyoo to generate reports as open document spreadsheets. pyoo can do everything I require bar setting column widths. Some I want to set as a constant, others as optimal width. From the pyoo website (https://github.com/seznam/pyoo): "If some important feature missing then the UNO API is always available."
A few hours of Googling got me to the class com.sun.star.table.TableColumn which from this page appears to have the properties ("Width" and "OptimalWidth") that I require, but -
>>> x = uno.getClass('com.sun.star.table.TableColumn')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/uno.py", line 114, in getClass
return pyuno.getClass(typeName)
uno.RuntimeException: pyuno.getClass: uno exception com.sun.star.table.TableColumn is unknown
I have no idea whatsoever how to get this to work. The documentation for UNO is overwelming to say the least...
Any clues would be enormously appreciated.
Example Python-UNO code:
def resize_spreadsheet_columns():
oSheet = XSCRIPTCONTEXT.getDocument().getSheets().getByIndex(0)
oColumns = oSheet.getColumns()
oColumn = oColumns.getByName("B")
oColumn.IsVisible = False
oColumn = oColumns.getByName("C")
oColumn.Width = 7000
oColumn = oColumns.getByName("D")
oColumn.OptimalWidth = True
Documentation:
https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/Rows_and_Columns
https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Columns_and_Rows
EDIT:
From the comment, it sounds like you need to work through an introductory tutorial on Python-UNO. Try http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html.
Thank you Jim K, you pointed me in the right direction, I got it working. My python script generates a ten sheet spreadsheet, and manually adjusting the column widths was becoming a pain. I post below my final code if anyone wants to comment or needs a solution to this. It looks like a pigs breakfast to me combining raw UNO calls and pyoo, but it works I guess.
#! /usr/bin/python3.6
import os, pyoo, time, uno
s = '-'
while s != 'Y':
s = input("Have you remembered to start Calc? ").upper()
os.system("soffice --accept=\"socket,host=localhost,port=2002;urp;\" --norestore --nologo --nodefault")
time.sleep(2)
desktop = pyoo.Desktop('localhost', 2002)
doc = desktop.create_spreadsheet()
class ofic:
sheet_idx = 0
row_num = 0
sheet = None
o = ofic()
uno_localContext = uno.getComponentContext()
uno_resolver = uno_localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", uno_localContext )
uno_ctx = uno_resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
uno_smgr = uno_ctx.ServiceManager
uno_desktop = uno_smgr.createInstanceWithContext( "com.sun.star.frame.Desktop", uno_ctx)
uno_model = uno_desktop.getCurrentComponent()
uno_controller = uno_model.getCurrentController()
uno_sheet_count = 0
for i in range(5):
doc.sheets.create("Page {}".format(i+1), index=o.sheet_idx)
o.sheet = doc.sheets[o.sheet_idx]
o.sheet[0, 0].value = "The quick brown fox jumps over the lazy dog"
o.sheet[1, 1].value = o.sheet_idx
uno_controller.setActiveSheet(uno_model.Sheets.getByIndex(uno_sheet_count))
uno_sheet_count += 1
uno_active_sheet = uno_model.CurrentController.ActiveSheet
uno_columns = uno_active_sheet.getColumns()
uno_column = uno_columns.getByName("A")
uno_column.OptimalWidth = True
uno_column = uno_columns.getByName("B")
uno_column.Width = 1350
o.sheet_idx += 1
doc.save("whatever.ods")
doc.close()
Python3 and OpenPyxl version 2.3.2
How do you remove a Scatter Chart Gridlines?
from openpyxl.chart.axis import ChartLines
SCchart = ScatterChart()
SCchart.title = "Scatter Chart"
SCchart.style = 13
SCchart.x_axis.majorGridlines = False
gives me the error:
TypeError: expected class 'openpyxl.chart.axis.ChartLines'
And this:
SCchart.x_axis.ChartLines.majorUnit = False
gives the error: AttributeError: 'NumericAxis' object has no attribute 'ChartLines'
I'd like to remove all the chart gridlines.
I have not been able to do this with Openpyxl 2.51, even using some tricks like setting the gridlines to the background color of white (hex 'FFFFFF'). I can get close to accessing the line parameter with openpyxl, but can't quite get it to work. I am including my efforts here, hoping some one else will pick up the ball.
The python gist:
from openpyxl.chart.shapes import GraphicalProperties
# turn majorGridlines off using shapes.GraphicalProperties
sgp = GraphicalProperties(solidFill='FFFFFF') # White
chart.y_axis.majorGridlines.spPr = sgp
This is the XML that openpyxl writes:
<valAx>
<axId val="2" />
<scaling>
<orientation val="minMax" />
<min val="0" />
</scaling>
<axPos val="l" />
<majorGridlines>
<spPr>
<a:solidFill>
<a:srgbClr val="FFFFFF" />
</a:solidFill>
<a:ln>
<a:prstDash val="solid" />
</a:ln>
</spPr>
</majorGridlines>
When I open the spreadsheet that openpyxl just wrote with Excel 2010, the major gridlines are still there with a dark grey color. I click on them and set their color to white and save the file with a new filename. This is how excel writes the new xml code:
<c:valAx>
<c:axId val="83446016"/>
<c:scaling>
<c:orientation val="minMax"/>
<c:min val="0"/>
</c:scaling>
<c:delete val="0"/>
<c:axPos val="r"/>
<c:majorGridlines>
<c:spPr>
<a:ln>
<a:solidFill>
<a:schemeClr val="bg1"/>
</a:solidFill>
<a:prstDash val="solid"/>
</a:ln>
</c:spPr>
</c:majorGridlines>
So logically, you might think that this python would work (spoiler, not for me!):
chart.y_axis.majorGridlines.spPr.ln = sgp
The proper method (the one used by Microsoft) is to set the gridlines to NoFill. Turning off gridlines in excel, saving the file and looking at the chart.xml file yields this:
<c:valAx>
<c:axId val="83031552"/>
<c:scaling>
<c:orientation val="minMax"/>
<c:min val="0"/>
</c:scaling>
<c:delete val="0"/>
<c:axPos val="r"/>
<c:majorGridlines>
<c:spPr>
<a:ln>
<a:noFill/>
<a:prstDash val="solid"/>
</a:ln>
</c:spPr>
</c:majorGridlines>
The python would be something like:
sgp = GraphicalProperties(noFill=True) # bonks, tried None also not effective
chart.y_axis.majorGridlines.spPr.ln = sgp
or maybe
chart.y_axis.majorGridlines.spPr.ln.noFill = True
which also bonks because there is no ln or line in this openpyxl path.
I just found an actual answer that works! You dont need to import ChartLines. The trick was I needed to include another class to get the line thing to work like this:
from openpyxl.drawing.line import LineProperties
# turn majorGridlines off using shapes.GraphicalProperties and drawing.LineProperties
sgp = GraphicalProperties(ln=LineProperties(noFill=True))
chart.x_axis.majorGridlines.spPr = sgp
Try it out!
Not sure if the earlier answers ended this thread, but based on those recommendations and a few tweaks I was able to enable/disable grid Lines for a Line Chart, add data labels.
The following code was used:
from openpyxl.chart.shapes import GraphicalProperties
from openpyxl.drawing.line import LineProperties
from openpyxl.chart.axis import ChartLines
from openpyxl.chart.label import DataLabelList
c1.y_axis.majorGridlines.spPr = GraphicalProperties(noFill = 'True')
c1.y_axis.majorGridlines.spPr.ln = LineProperties(solidFill = '000000')
c1.x_axis.majorGridlines = ChartLines()
c1.x_axis.majorGridlines.spPr = GraphicalProperties(noFill = 'True')
c1.x_axis.majorGridlines.spPr.ln = LineProperties(solidFill = '000000')
c1.dLbls = DataLabelList()
c1.dLbls.showVal = 1
Basically, certain parameters 1st need a class instance to be assigned to them in order to change subsequent sub-parameters.
For ex. When you try to set a value to spPr, the error thrown back will specify the class it expected, which you can then import and assign it's instance to the variable, if I may call it that. Beyond that, the xml can greatly help you figure which variables need to be changed. Hope this helps..
I successfully removed the gridlines from my chart by setting majorGridlines to None.
I included the following two lines in my script.
c1.x_axis.majorGridlines = None
c1.y_axis.majorGridlines = None
In my case, c1 is the instance of openpyxl.chart.LineChart().
I came up with this solution after noticing that majorGridlines accepts None as a value. I noticed this while reading the class definition for _BaseAxis which can be found here:
https://openpyxl.readthedocs.io/en/latest/_modules/openpyxl/chart/axis.html
Below is a full example program. Note: file paths are for windows so you may have to tweak these if you want to run the script on your machine.
# Generate Plots With No Grid Lines
import openpyxl as xl
import numpy as np
from pathlib import Path
# Create Sheet 1 Data
years = np.arange(2000,2023,1)
x1 = np.linspace(0,20,years.size)
x2 = np.linspace(10,2,years.size)
# Create Sheet 2 Data
x3 = np.linspace(10,100,years.size)
x4 = np.linspace(120,50,years.size)
# Open Workbook and Write Sheet 1
wb = xl.Workbook()
sheet = wb[wb.sheetnames[0]]
sheet_one_title = 'Data One'
sheet.title = sheet_one_title
sheet.append(['Year','X1','X2'])
for i in range(0,years.size):
sheet.append([years[i],x1[i],x2[i]])
# Create Sheet 2 and Switch to It
sheet_two_title = "Data Two"
wb.create_sheet(title=sheet_two_title)
sheet = wb[sheet_two_title]
# Write To Sheet 2
sheet.append(['Year','X3','X4'])
for i in range(0,years.size):
sheet.append([years[i],x3[i],x4[i]])
# Now Add The Charts
# Starting With Sheet Two (i.e. "Data Two")
c2 = xl.chart.LineChart()
data = xl.chart.Reference(sheet, min_col=2, min_row=1, max_col=3, max_row=years.size+1)
c2.add_data(data, titles_from_data=True)
dates = xl.chart.Reference(sheet, min_col=1, min_row=2, max_row=years.size+1)
c2.set_categories(dates)
# REMOVE THE GRIDLINES
c2.x_axis.majorGridlines = None
c2.y_axis.majorGridlines = None
# Add Chart to Sheet
sheet.add_chart(c2, 'D5')
# Swtich Back To Sheet 1 (i.e. "Data One")
sheet = wb[sheet_one_title]
# Create Chart
c1 = xl.chart.LineChart()
data = xl.chart.Reference(sheet, min_col=2, min_row=1, max_col=3, max_row=years.size+1)
c1.add_data(data, titles_from_data=True)
dates = xl.chart.Reference(sheet, min_col=1, min_row=2, max_row=years.size+1)
c1.set_categories(dates)
# REMOVE THE GRIDLINES ONCE MORE
c1.x_axis.majorGridlines = None
c1.y_axis.majorGridlines = None
# Add Chart to Sheet
sheet.add_chart(c1, 'D5')
# Get Route to Desktop
desktop = str(Path.home()) + "\Desktop"
# Create Path by Appending File Name
save_path = desktop + "\\PlotExample.xlsx"
# Save Workbook
wb.save(save_path)
print("Workbook Saved To:" + save_path)
p.s. this is my first ever stack overflow answer :)
from fipy import *
nx = 50
dx = 1.
mesh = Grid1D(nx=nx, dx=dx)
phi = CellVariable(name="solution variable",
mesh=mesh,
value=0.)
D = 1.
valueLeft = 1
valueRight = 0
phi.constrain(valueRight, mesh.facesRight)
phi.constrain(valueLeft, mesh.facesLeft)
eqX = TransientTerm() == ExplicitDiffusionTerm(coeff=D)
timeStepDuration = 0.9 * dx**2 / (2 * D)
steps = 100
phiAnalytical = CellVariable(name="analytical value",
mesh=mesh)
viewer = Viewer(vars=(phi, phiAnalytical),
datamin=0., datamax=1.)
viewer.plot()
x = mesh.cellCenters[0]
t = timeStepDuration * steps
try:
from scipy.special import erf
phiAnalytical.setValue(1 - erf(x / (2 * numerix.sqrt(D * t))))
except ImportError:
print "The SciPy library is not available to test the solution to \
the transient diffusion equation"
for step in range(steps):
eqX.solve(var=phi,
dt=timeStepDuration)
viewer.plot()
I am trying to implement an example from the fipy examples list which is the 1D diffusion problem. but I am not able to view the result as a plot.
I have defined viewer correctly as suggested in the code for the example. Still not helping.
The solution vector runs fine.
But I am not able to plot using the viewer function. can anyone help? thank you!
Your code works fine on my computer. Probably is a problem with a plotting library used by FiPy.
Check if the original example works (just run this from the fipy folder)
python examples/diffusion/mesh1D.py
If not, download FiPy from the github page of the project https://github.com/usnistgov/fipy and try the example again. If not, check if the plotting libraries are correctly installed.
Anyways, you should specify the platform you are using and the errors you are getting. The first time I had some problems with the plotting libraries too.