I tried adjusting this code of Haar wavelet transform to work with OpenCV.js. The recursion works fine but the colors of the resulting image are all messed up. Here's a screenshot of my results:
Here's what the output should look like:
And here's my code:
function OneDHaarTransform(HaarMatrix)
{
var sum = 0;
var diff = 0;
var hMLen = HaarMatrix.length/2;
var tempHaar = [];
//It only recurses on first half of the array
for (var i = 0; i < hMLen; i++)
{
sum = HaarMatrix[2*i] + HaarMatrix[2*i + 1];
sum = sum / Math.sqrt(2);
diff = HaarMatrix[2*i] - HaarMatrix[2*i + 1];
diff = diff / Math.sqrt(2);
tempHaar[i] = sum;
tempHaar[i + hMLen] = diff
};
for (var i = 0; i < HaarMatrix.length; i++) {
HaarMatrix[i] = tempHaar[i];
};
};
function haarTransform(img, MaxStepHaar)
{
var width = img.cols;
var height = img.rows;
var currWidth = width;
var currHeight = height;
let pix=img.clone();
let altpix=[];
var rowSize = width;
var colSize = height;
// var Haar = [];
var Haar = createArray(height,width,3);
var tempHaar = [];
let dst = img.clone();
//Initialize the Haar matrix
for (var row = 0; row < height; row++)
{
for (var col = 0; col < width; col++) {
for (var i = 0; i < 3; i++) {
let pixel = pix.ucharPtr(row,col);
Haar[row][col][i] = pixel[i];
};
};
};
//Do a Haar Wavelet Transform
while( (currWidth > 1 || currHeight > 1) && (MaxStepHaar > 1) )
{
MaxStepHaar = MaxStepHaar - 1;
//Do it for each row first
if (currWidth > 1)
{
for(var row = 0; row < currHeight; row++)
{
for (var i = 0; i < 3; i++) {
for(col = 0; col < currWidth; col++) {
tempHaar[col] = Haar[row][col][i];
};
OneDHaarTransform(tempHaar);
for(col = 0; col < currWidth; col++) {
Haar[row][col][i] = tempHaar[col];
};
};
};
};
//Then perform Haar transform on each column
tempHaar = [];
if (currHeight > 1)
{
for(var col = 0; col < currWidth; col++)
{
for (var i = 0; i < 3; i++) {
for(row = 0; row < currHeight; row++) {
tempHaar[row] = Haar[row][col][i];
};
OneDHaarTransform(tempHaar);
for(row = 0; row < currHeight; row++) {
Haar[row][col][i] = tempHaar[row];
};
};
};
};
tempHaar = [];
if (currHeight > 1) {currHeight = currHeight/2};
if (currWidth > 1) {currWidth = currWidth/2};
};
//Copy pix data to canvas
for (var row = 0; row < height; row++) {
for (var col = 0; col < width; col++) {
pixel[0] = Haar[row][col][0];
pixel[1] = Haar[row][col][1];
pixel[2] = Haar[row][col][2];
pixel[3] = 1;
};
};
pix.delete();dst.delete();
};
I only changed it so the input and output would be Mat() objects. I've tried to see if the maximum value of the Mat() exceeds 255, but it doesn't. I don't know what went wrong, please help.
Related
function selectTo(cell) {
var row = cell.parent();
var cellIndex = cell.index();
var rowIndex = row.index();
var rowStart, rowEnd, cellStart, cellEnd;
if (rowIndex < startRowIndex) {
rowStart = rowIndex;
rowEnd = startRowIndex;
sessionStorage.setItem('rowStart', rowStart);
sessionStorage.setItem('rowEnd', rowEnd);
} else {
rowStart = startRowIndex;
rowEnd = rowIndex;
sessionStorage.setItem('rowStart', rowStart);
sessionStorage.setItem('rowEnd', rowEnd);
}
if (cellIndex < startCellIndex) {
cellStart = cellIndex;
cellEnd = startCellIndex;
sessionStorage.setItem('cellStart', cellStart);
sessionStorage.setItem('cellEnd', cellEnd);
} else {
cellStart = startCellIndex;
cellEnd = cellIndex;
sessionStorage.setItem('cellStart', cellStart);
sessionStorage.setItem('cellEnd', cellEnd);
}
for (var i = rowStart; i <= rowEnd; i++) {
var TableID = sessionStorage.getItem("TableID");
var table6 = document.getElementById(TableID);
var row6 = table6.getElementsByTagName('tr')[i];
var rowCells = row6.getElementsByTagName('td');
for (var j = cellStart; j <= cellEnd; j++) {
rowCells[j].className = "hover";
}
}
}
var TableID = sessionStorage.getItem("TableID");
var cellStart = sessionStorage.getItem("cellStart");
var cellEnd = sessionStorage.getItem("cellEnd");
var rowStart = sessionStorage.getItem("rowStart");
var rowEnd = sessionStorage.getItem("rowEnd");
for (var i = rowStart; i <= rowEnd; i++) {
var myTable = document.getElementById(TableID);
var row10 = myTable.getElementsByTagName('tr')[i];
var rowCells = row10.getElementsByTagName('td');
for (var j = cellStart; j < cellEnd; j++) {
if (j === cellStart && i === rowStart)
continue;
//rowCells[j].style.display = "none";
myTable.rows[i].deleteCell(j);
}
}
When I delete cells, use a different method table.row[i].deleteCell(j); or removechild I get out of range error.
mesage:
Uncaught DOMException: Failed to execute 'deleteCell' on
'HTMLTableRowElement': The value provided (3) is outside the range [0,
3).
at init.callback
I find solution:
var listHover = document.querySelectorAll('.hover');
for (var i = 0; i < listHover.length; i++) {
if (i > 0) {
listHover[i].style.display = 'none';
}
}
I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}
I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}
I create 2d array with random number
<script type="text/javascript">
function matrixArray(rows, columns) {
var min = 0;
var max = 10;
var arr = new Array();
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < columns; j++) {
arr[i][j] = Math.floor(Math.random() * (max - min + 1)) + min;
}
}
return arr;
}
</script>
Now i wont write function that create table with delete button in all rows. And function that delete row from array and redraw the table. Try like this, but not working
<script>
function createtab (arr)
{
var inpts = [], t = document.createElement('TABLE');
t.cellSpacing = 0, t.cellPadding = 5, t.border = 1;
for (var j = 0, J = arr.length; j < J; j++) {
var ro = t.insertRow(-1),
ce = ro.insertCell(-1),
inpt = document.createElement('INPUT');
inpt.type = 'button', inpt.value = 'Delete', inpt.onclick = 'rowdel(arr,'+j+')';
inpts.unshift(ce.appendChild(inpt));
for (var k = 0, K = arr[j].length; k < K; k++) { var ce = ro.insertCell(-1); ce.innerHTML = arr[j][k] }
}
var obj = document.getElementById('forTable').appendChild(t);
}
</script>
delete row on button click
<script>
function rowdel(arr, i) {
arr.splice(i, 1);
createtab(arr);
}
</script>
html body
<body>
<div id="forTable"></div>
<script>
var arr = matrixArray(6, 7);
createtab(arr);
</script>
</body>
EDITED
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var arr = matrixArray(6, 7);
createtab(arr);
});
function matrixArray(rows, columns) {
var min = 0;
var max = 10;
var arr = new Array();
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < columns; j++) {
arr[i][j] = Math.floor(Math.random() * (max - min + 1)) + min;
}
}
return arr;
}
function createtab (arr)
{
var inpts = [], t = document.createElement('TABLE');
t.cellSpacing = 0, t.cellPadding = 5, t.border = 1;
for (var j = 0, J = arr.length; j < J; j++) {
var ro = t.insertRow(-1),
ce = ro.insertCell(-1),
inpt = document.createElement('INPUT');
inpt.type = 'button', inpt.value = 'Delete',inpt.attributes['id']=j, inpt.onclick =function() { rowdel(arr,this)};
inpts.unshift(ce.appendChild(inpt));
for (var k = 0, K = arr[j].length; k < K; k++) { var ce = ro.insertCell(-1); ce.innerHTML = arr[j][k];
//alert(j);
}
}
var obj = document.getElementById('forTable').appendChild(t);
}
function rowdel(arr,input) {
var i = input.attributes['id'];
arr.splice(i, 1);
$('#forTable').empty();
createtab(arr);
}
</script>
<body>
<div id="forTable"></div>
</body>
you don't need to redraw the table .
inpt.onclick = 'rowdel(arr,'+j+',this)';
function rowdel(arr, i, input) {
arr.splice(i, 1);
var row = input.parentNode.parentNode;
row.parentNode.removeChild(row);
}
UPDATE: onclick requires a function
inpt.attributes['id']=j;
inpt.onclick = function () {
rowdel(this);
};
function rowdel(input) {
var i = input.attributes['id'];
arr.splice(i, 1);
var row = input.parentNode.parentNode;
row.parentNode.removeChild(row);
}
you can define you del function such like that.
var dele = function rowdel(arr, i) {
return function(){
arr.splice(i, 1);
createtab(arr);
}
}
and use it as like closures as .
inpt.type = 'button', inpt.value = 'Delete', inpt.onclick = dele(arr, j);
When I generate this table it is generated after the rest of the code is executed.
I want to be able to generate the code into a specific class like ".container".
How would I do this?
var listOfWords = [];
var rndWord = [];
var counter = 0;
var ul = document.getElementById("wordlist");
var i;
for (i = 0; i < ul.children.length; ++i) {
listOfWords.push({
"name": ul.children[i].getAttribute("data-word"),
"pic": ul.children[i].getAttribute("data-pic"),
"audio": ul.children[i].getAttribute("data-audio")
});
}
var chosenWords = [];
var copylist = listOfWords.slice();
for (var x = 0; x < 6; x++) {
var rand = Math.floor(Math.random() * (copylist.length));
chosenWords.push(copylist[rand].name);
copylist.splice(rand, 1);
if (chosenWords.length < 12) {
chosenWords.push(' ');
}
}
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() {
return 0.5 - Math.random()
});
var guesses = {};
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop-box').attr('data-word', word).attr('data-letter', word[k]);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
I thought changing the bottom line of this code from
document.body.appendChild(tbl);
to
document.container.appendChild(tbl);
would do it but it didn't.
Does anyone know how to put this table into container?
If you want to add the table to an element with a specific css class, you can do the following.
$(".container").append(tbl);