I'm trying to develop a javascript code using opencv.js, I have python code with the same requirement, I converted many lines but some are very hard to find, please guide me.
last 3 lines from python code unable to find for javascript opencv.js.
def find_marker(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 35, 125)
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts) //these three line are unable to find for javascript.
c = max(cnts, key = cv2.contourArea)
return cv2.minAreaRect(c)
In the first line, the code is using the function in imutils python package. If you see the grab_contours method in imutils.convenience file located at https://github.com/jrosebr1/imutils/blob/master/imutils/convenience.py, you can see how it is implemented.
This is very simple to implement as a one liner in js.
cnts = (cnts.length == 2) ? cnts[0] : (cnts.length == 3) ? cnts[1] : cnts
In second line, max is the inbuilt function of python for iterating through an iterable and to find the maximum based on the key.
This same functionality can be achieved in js as follows
c = cnts.reduce(function(max, cur) {
// here key is the cv2.contourArea function,
// we apply that on the cnts[i] and finds the cnts[i]
// such that cv2.contourArea(cnts[i]) is maximum
if(cv2.contourArea(max) < cv2.countourArea(cur)) {
return cur
} else {
return max
}
});
Now for the third line I assume cv2.minAreaRect function is present in the js version too. I'm not sure though. But hope the above code works for you. Thank you.
Related
Just started learning how to write functions in Google Script Editor. Please help me fix my error. I'm also unable to get the Logger.log(var) function to produce anything in the log.
Goal of the function: count attendance based on whether an 'X' was listed next to a name. Currently the range being iterated through is hard coded. Is it possible to pass through a custom range when the function is called?
Thank you.
function attendance() {
var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var count = 0
for (n=6; n<12;++n){
var cell = values[n][2];
if (cell == "X"){
count = count +1;
}
}
return (count);
}
Yes, you can use the length of the values array to make it more dynamic.
n < values.length
I have a uncyclic directed graph, represented by a dictionnary (example {1: [2,3] , 2:[], 3: [4], 4:[]} ).
I want to find the size of the longest branch from a given source vertex, let say 1 for this example.
I wrote following javascript recursive function:
function computeLongest(graph, node){
if (graph[node].length === 0){
return 1;
}
else{
var l = [];
for (var i=0; i < graph[node].length; i++){
l.push(computeLongest(graph, graph[node][i]));
}
return 1+Math.max(l);
}
}
If I test this function with previous example, simple tree which looks like :
1
/ \
2 3
\
4
My result is 2 and not 3. It looks like my list l is beeing modified in the recursive calls of the function.
If I write the same function in Python, it works fine.
Are there any differences between Python and Javascript in the way we handle recursion and associated variables ? I don't understand why the behaviour is not the same.
Python code:
def c(graph, number):
if len(graph[number]) == 0:
return 1
l = []
for child in graph[number]:
l.append(c(graph, child))
return 1+max(l)
Your issue is probably from a difference in max implementation.
The max function in python doesn't behave like Math.max in javascript. If given an array, Python will find a way to get the maximum value out of it. Javascript will not. In javascript, the expected input is a list of arguments, e.g Math.max(1,4,3,2).
Ex:
Python
max([1,4,3,2]) # returns 4
Javascript
Math.max([1,4,3,2]) # returns NaN
In fact, I am surprised that your javascript code works.
Update
As stated in the comments, you may use the spread operator ... to use Math.max with an array and still, provide the expected input.
Math.max(...[1,4,3,2]) is equivalent to Math.max(1,4,3,2), hence Math.max(...l) will expand in Math.max(l[0], l[1]... l[N]).
Actually, question is - how to recreate type of formulas:
ArrayFormula(replace(replace(regexreplace(K1:K&"","[-/,. ()]",""),4,0,"-"),8,0,"-"))
into code. Unfortunately, i didn't find it by myself, so I'm asking for help.
Upd.
Let me clarify just a little.
Part of code which was used by me into script:
value = value.replace(/^ /, '').replace(/[. )]/g, 'a').replace(/[+]/g, '').replace(/(aa)/g, '-').replace(/(a)/g, '-').replace(/[(]/g, '-');
value = value.replace(/^-/, '');
value = value.replace(/-$/, ''); range2.setValue(value);
This is example of a result:
"(22)road.CA" - "22-road-CA";
"22roadCA" - is not(eror).
If we working into google spreadsheets we could use formula's which I'm typed before, and in this case, results will be the:
"(22)road.CA" - "22-road-CA";
"22roadCA" - "22-road-CA".
So, how to create right code for it? Mb I should delete all signs, use looping method for check sign by sign, and insert my variant after some count of cell array?
Simple example :
var formulaTargetCell = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet()
.getRange(1, 1, 1, 1);
formulaTargetCell.setFormula('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))');
//or
var formulaTargetCell = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet()
.getRange('B2');
formulaTargetCell.setFormulaR1C1('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))');
There are still some kind of way to set formula in app script that documented in available API of Range
I am having a problem working out how to chain syncs in Office JS - I think I have to do one sync to read the values then another sync to write them back - must be simple but I can't find a chaining example.
Basically I am trying to code the equivalent of this VBA code which does a read and a write via an array
Application.ScreenUpdating = False
d1 = MicroTimer
Set rng1 = Worksheets("Sheet1").Range("A1:A1000")
Set rng2 = Worksheets("Sheet1").Range("D1:D1000")
var = rng1.Value2
rng2.Value2 = var
d2 = (MicroTimer - d1) * 1000
MsgBox d2
or even simpler
Worksheets("Sheet1").Range("D1:D1000").Value2=Worksheets("Sheet1").Range("A1:A1000").Value2
To copy the values from one range to another, you can use the following code:
Excel.run(function(context) {
var range1 = context.workbook.worksheets.getItem("Sheet1").getRange("A1:A1000").load('values');
return context.sync()
.then(() => {
var range2 = context.workbook.worksheets.getItem("Sheet1").getRange("D1:D1000");
range2.values = range1.values;
return context.sync();
});
});
You can use the Range-Class OfficeJS gives you.
Here is the full doc: https://dev.office.com/reference/add-ins/excel/range (Also have a look at the examples given there)
To copy the Range, you need to create both ranges and copy the .values[][] from the source to the dest.
For how to copy a two-dimensional array (in this case: values[][]), you should use google.
To Determine the time, you can use the Date()-Class Java gives you.
I have a directed graph where paths are stored in JSON array like. It is in the form of source and destination .
Var pathDirection = [{"Source":2,"Destination":3},
{"Source":3,"Destination":4},
{"Source":5,"Destination":4},
{"Source":2,"Destination":5},
{"Source":4,"Destination":6}];
Using above it forms graph like below structure .
My problem is I don’t know the starting point and I have to find all possible path to reach 6 from any node
Like for above graph different path to reach 6 is
Output:
[4 ->6]
[3->4 ->6]
[5->4 ->6]
[2->5->4 ->6]
[2->3->4 ->6]
I have tried to write below algo using backtracking which is working fine but looking for some best algo to find. Please suggest any other possible way to do same and how can i optimize below programe.
// BackTrack From End Node Destination 6
var getAllSource = function(destId){
var sourceForsameDist = [];
pathDirection.forEach(function(eachDirection){
if(eachDirection.Destination == destId){
sourceForsameDist.push(eachDirection.Source);
}
});
return sourceForsameDist;
};
var diffPath = [];
var init = function(destination){
var sourceId = getAllSource(destination[destination.length - 1]);
if(sourceId.length === 0){
diffPath.push(destination);
}
for(var i=0;i<sourceId.length;i++){
var copy = destination.slice(0);
copy.push(sourceId[i]);
init(copy);
}
};
init([6]);
console.log(diffPath); // [[6,4,3,2],[6,4,5,2]]
I have tried to do using backtracking which is working fine but looking for some best algo to find.
I'd call it Depth-First-Search instead of backtracking, but yes the algorithm is fine.
However, I'd have some suggestions on the implementation:
make diffPath a local variable and return it from the init function
If you omit the if(sourceId.length === 0) condition then you will get the expected output, not only the the paths from the sources
instead of looping through the whole pathDirections in your getAllSource function, I'd use a lookup table that is filled before starting the traversal
rename init to something more meaningful