I can't understand this shape from the python code - python-3.x

I'm new to python. I'm searching on google about python code to get street sign detection, I found some code but I can't understand what the code means.
elif dominant_color[0] > 80:
zone_0 = square[square.shape[0]*3//8:square.shape[0]
* 5//8, square.shape[1]*1//8:square.shape[1]*3//8]
cv2.imshow('Zone0', zone_0)
zone_0_color = warnadominan(zone_0, 1)
zone_1 = square[square.shape[0]*1//8:square.shape[0]
* 3//8, square.shape[1]*3//8:square.shape[1]*5//8]
cv2.imshow('Zone1', zone_1)
zone_1_color = warnadominan(zone_1, 1)
zone_2 = square[square.shape[0]*3//8:square.shape[0]
* 5//8, square.shape[1]*5//8:square.shape[1]*7//8]
cv2.imshow('Zone2', zone_2)
zone_2_color = warnadominan(zone_2, 1)
Thanks in advance

Assuming square has shape (8, 8)
I think this diagram might help:
Edit: The code is trying to extract the zones shown in the image

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')

networkx output scale problem with matplotlib (re-post)

I'm re-posting this question since I didn't make a good example code in last question.
I'm trying to make a nodes to set in specific location.
But I found out that the output drawing is not... fixed. Let me show you the pic.
So this is the one I make with 10 nodes. worked perfectly as I intended.
Also it has plt.text on the bottom left.
And here's the other picture
As you can see, something is wrong. plt.text is gone, and USA's location is weird. Actually that location is where DEU is located in the first pic. Both pics use same code.
Now, let me show you some of my code.
for spec_df, please download from my gdrive:
https://drive.google.com/drive/folders/11X_i5-pRLGBfQ9vIwQ3hfDU5EWIfR3Uo?usp=sharing
auto_flag = 0
spec_df=pd.read_stata("C:\\"Your_file_loc"\\CombinedHS6_example.dta")
#top_10_list = ["USA","CHN","KOR"] (Try for three nodes)
#or
#auto_flag = 1 (Try for 10 nodes)
df_p = spec_df[['partneriso3','tradevalue']]
df_p = df_p.groupby('partneriso3').sum().reset_index()
df_r = spec_df[['reporteriso3','tradevalue']]
df_r = df_r.groupby('reporteriso3').sum().reset_index()
df_r = df_r.rename(columns={'reporteriso3': 'Nation'})
df_r = df_r.rename(columns={'tradevalue': 'tradevalue_r'})
df_p = df_p.rename(columns={'partneriso3': 'Nation'})
df_s = pd.merge(df_r, df_p, on='Nation', how='outer').fillna(0)
df_s["final"] = df_s['tradevalue'] + df_s['tradevalue_r']
if auto_flag == 1:
df_s = df_s.sort_values(by=['final'], ascending = False).reset_index()
cut = df_s[:10]
else:
cut = df_s[(df_s['Nation'].isin(top_10_list))]
cut['final'] = cut['final'].apply(lambda x: normalize(x, cut['final'].max()))
cut['font_size'] = cut['final'] * 13
cut['final'] = cut['final'] * 1500
top_10_list = list(cut["Nation"])
top10 = spec_df[(spec_df['reporteriso3'].isin(top_10_list))&(spec_df['partneriso3'].isin(top_10_list))]
top10['tradevalue'] = top10['tradevalue'].apply(lambda x: normalize(x, top10['tradevalue'].max()))
top10['tradevalue'] = top10['tradevalue']*10
plt.figure(figsize=(10,10), dpi = 100)
G = nx.from_pandas_edgelist(top10, 'reporteriso3', 'partneriso3', 'tradevalue', create_using= nx.DiGraph())
widths = nx.get_edge_attributes(G,'tradevalue')
pos = {}
pos_cord = [(-0.30779309, -0.26419882), (0.26767895, 0.19524759), (-0.38479095, 0.88179998), (0.33785317, 0.96090914), (0.94090464, 0.40707934), (0.9270665, -0.38403114), (0.41246223, -0.85684049), (-0.32083322, -1.0), (-0.99724456, -0.34947554), (-0.87530367, 0.40950993)]
for t in range(len(top_10_list)):
if top_10_list == "":
continue
else:
pos[top_10_list[t]] = pos_cord[t]
pos_nodes = nudge(pos, 0, 0.12)
nx.draw_networkx_edges(G,pos, width=list(widths.values()), edge_color = '#9ECAE4')
nx.draw_networkx_nodes(G, pos=pos, nodelist = cut['Nation'], node_size= cut['final'], node_color ='#AB89EF', edgecolors ='#000000')
nx.draw_networkx_labels(G,pos_nodes, font_size=15)
plt.text(-1.15,-1.15,s='hs : ')
plt.savefig(location,dpi=300)
Sorry for the crude code. But I want to ask that I'm using fixed coordinates. So nodes are not supposed to move there location. So I think the plt's size is kinda interacting with the contents...? But I don't know how it does that.
Could anyone enlighten me please? This drives me crazy...
Thanks to #Paul Brodersen's comment, I found a way to fix the location.
I just added these codes in my codes.
fig = plt.figure(figsize=(10,10), dpi = 100)
axes = fig.add_axes([0,0,1,1])
axes.set_xlim([-1.3,1.3])
axes.set_ylim([-1.3,1.3])
Thank you for the help again!

Python code to node.js

I found this part in a python code:
score = random.randint(0, 100)
filled_progbar = round(score / 100 * 10)
counter_ = '█' * filled_progbar + '‍ ‍' * (10 - filled_progbar)
It looks good in python but I don't know how I can put this in node.js.
Why I need this from python to node.js?
Because I am dumb to python and I am newbie in the node.js and therefore I am asking here. :)
Sorry if I didn't choose the right tags but I am not sure which tag would be good to this.
If my research is correct then the score part would be so:
Math.floor(Math.random() * 100);
But I don't know the other part.
It seems pointless but fun so I gave it a go,
const score = parseInt(Math.random()*100);
const filled_progbar = Math.round(score/10.0);
const counter_ = '█'.repeat(filled_progbar) + '‍ ‍'.repeat(10 - filled_progbar)
console.log(counter_);

fipy viewer not plotting

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.

How to find data between two values

I am trying to find the data between two values. I am using this code in a GUI programme, the starting_value and ending_value which you can see in the code below are selected from 2 listboxes in a previous part of the code.
% --- Executes on button press in CalculateIntensity.
function CalculateIntensity_Callback(hObject, eventdata, handles)
% hObject handle to CalculateIntensity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Trapz function
starting_value = getappdata(0,'StartValue');
ending_value = getappdata(0,'EndValue');
StartingValue = str2mat(starting_value)
EndingValue = str2mat(ending_value)
A = getappdata(0,'XYarray')
data_found = A(A(:,[1,2]) > StartingValue & A(:,[1,2]) < EndingValue)
I found help on:
http://www.mathworks.com/matlabcentral/answers/8556-how-to-find-vector-elements-between-two-values-efficiently
However the
data_found = A(A(:,[1,2]) > StartingValue & A(:,[1,2]) < EndingValue)
part of the code wont work for me, I think starting_value and ending_value are strings so I tried converting it to a matrix but I get the error:
Error using <
Matrix dimensions must agree.
Error in MichelleLaycockGUImainwindow>CalculateIntensity_Callback (line 119)
data_found = A(A(:,[1,2]) > StartingValue & A(:,[1,2]) < EndingValue)
an example of data used is:
A =
1.0e+03 *
0.1660 1.1570
0.1664 0.4650
0.1668 0
0.1672 1.0200
0.1676 1.0110
0.1680 1.0200
0.1684 1.0640
0.1688 1.1100
0.1692 1.0370
0.1696 1.0050
0.1700 1.0750
0.1704 1.0850
0.1708 1.1310
0.1712 1.0630
0.1716 1.0370
0.1719 1.1070
0.1724 1.1450
I'm not really sure where I'm going wrong, any help would be greatly appreciated as it's all I need to complete my work. Thanks in advance!
As some of the values in my data vary rather than just decreasing or increasing the greater than or equal to method I was originally trying to use did not work. So rather than using the loop to get the data between the two points selected I went with a different method.
I use[~,indx1]=ismember(StartingValue,A,'rows') this finds the row number of the selected data and then I use this information to extract the data between and including the selected data.
Here is the full code I used to do this:
starting_value = getappdata(0,'StartValue');
ending_value = getappdata(0,'EndValue');
StartingValue = str2num(starting_value);
EndingValue = str2num(ending_value);
A = getappdata(0,'XYarray');
[~,indx1]=ismember(StartingValue,A,'rows');
[~,indx2]=ismember(EndingValue,A,'rows');
arrayfortrapz = A(indx1:indx2,1:2); %array of data including and between selected data
I hope this of some help to anybody that may run into a similar issue.

Resources