Accessing pixel pointer - pixel

Can you explain to me how the accessing pixel has been done in this double loop ? how do they change rows and cols and pixel's value?
for(int i=0;i<cv_ptr->image.rows;i++)
{
float* ptr_img_A = cv_ptr->image.ptr<float>(i);
for(int j=0;j<cv_ptr->image.cols;j++)
{
*ptr_img_B=255*(*ptr_img_A)/3.5;
ptr_img_A++;
}
}
Thank you.

First of, is this the complete code or is ptr_img_B actually ptr_img_A in the first row of the inner loop?
Secondly I would recommend naming your variables by the content it has.
for(int i=0;i<cv_ptr->image.rows;i++)
{
float* row_ptr = cv_ptr->image.ptr<float>(i);
for(int j=0;j<cv_ptr->image.cols;j++)
{
*row_ptr=255*(*row_ptr)/3.5;
row_ptr++;
}
}
So basically it scales every pixel in the image with the factor of 255/3.5
Regarding the access of the pixel, it is stored in memory like this
COL
ROW 1 2 3 4
1 0 1 2 3
2 4 5 6 7
3 8 9 10 11
4 12 13 14 15
Then in order to access, for example pixel on row 3, col 2
float* row_ptr = cv_ptr->image.ptr<float>(row-1);
float value = row_ptr[col-1];
Finally I hope you will enjoy your time with openCV, it is a really nice framework :)

Related

Rotate Image - Java

I am doing a question where, given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. This my my code:
class Solution {
public void rotate(int[][] matrix) {
int size = matrix.length;
for(int i = 0 ; i < matrix.length; i++){
for(int y = 0 ; y < matrix[0].length ; y++){
matrix[i][y] = matrix[size - y - 1][i];
System.out.println(size - y - 1);
System.out.println(i);
System.out.println("");
}
}
}
}
This is the input and output results:
input matrix: [[1,2,3],[4,5,6],[7,8,9]]
output matrix: [[7,4,7],[8,5,4],[9,4,7]]
expected matrix: [[7,4,1],[8,5,2],[9,6,3]]
I do not really understand why I am getting duplicates in my output such as the number seven 3 times. On my System.out.println statement, I am getting the correct list of indexes :
2
0
1
0
0
0
2
1
1
1
0
1
2
2
What can be wrong?
I have found a solution. I will try my best to explain it.
Let us consider an array of size 4.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now lets look at the numbers present only on the outside of the array:
1 2 3 4
5 8
9 12
13 14 15 16
We will proceed by storing the first element 1 in a temporary variable. Next we will replace 1 by 13, 13 by 16, 16 by 4 and at last 4 by 1 (whose value we already stored in the temporary variable).
We will do the same for all the elements of the first row.
Here is a pseudocode if you just want to rotate this outer ring, lets call it an outer ring:
for i = 0 to n-1
{
temp = A[0][i];
A[0][i] = A[n-1-i][0];
A[n-1-i][0] = A[n-1-0][n-1-i];
A[n-1-0][n-1-i] = A[i][n-1-0];
A[i][n-1-0] = temp;
}
The code runs for a total of n times. Once for each element of first row. Implement this code an run it. You will see only the outer ring is rotated. Now lets look at the inner ring:
6 7
10 11
Now the loop in pseudocode only needs to run for 2 times and also our range of indexes has decreased. For outer ring, the loop started from i = 0 and ended at i = n-1. However, for the inner ring the for loop need to run from i = 1 to i = n-2.
If you had an array of size n, to rotate the xth ring of the array, the loop needs to run from i = x to i = n-1-x.
Here is the code to rotate the entire array:
x = 0;
int temp;
while (x < n/2)
{
for (int i = x;i < n-1-x;i++)
{
temp = arr[x][i];
arr[x][i] = arr[n-1-i][x];
arr[n-1-i][x] = arr[n-1-x][n-1-i];
arr[n-1-x][n-1-i] = arr[i][n-1-x];
arr[i][n-1-x] = temp;
}
x++;
}
Here each value of x denotes the xth ring.
0 <= x <= n-1
The reason why the outer loop runs only for x < n/2 times is because each array has n/2 rings when n is even and n/2 + 1 rings if n is odd.
I hope I have helped you. Do comment if face any problems with the solution or its explanation.

how to get the moore neighbourhood using index of a vector

I have a matrix in Rcpp (C++ for R) which is stored in column order in memory. Ie, it looks like:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Now, I have a single for loop that runs from i = 1 to 25 (bear in mind, it is all zero based, but here I am just saying one for convenience).
For every element of the matrix, I want its Moore neighbourhood. This is easy for the elements that are not on the edge. So if our selected index is idx and the size of the square matrix is nrow then we have
leftmid = idx - nrow
lefttop = (idx - nrow) - 1
leftbot = (idx - nrow) + 1
rightmid = idx + nrow
righttop = (idx + nrow) - 1
rightbot = (idx + nrow) + 1
midtop = idx - 1
midbot = idx + 1
But i cant figure out how to deal with the edge cases. For example, if idx = 3, then i want the neighbours:
leftmid = 23
lefttop = 22
leftbot = 24
rightmid = 8
righttop = 7
rightbot = 9
midtop = 2
midbot = 4
It's a little bit more complicated at the corner cases as well. My goal here is to reduce time. I am currently running my program with a double for loop which works, but is slower than reasonable. I want to change it into a single for loop to improve performance.
Edit: I realized the left and right boundaries can be obtained by modulus. So 3 - 5 %% 25 = 23. But I still have the top and bottom edge cases.
It appears you're interested in "cyclic" boundary conditions, where the matrix has a toroidal topology, i.e. the top wraps around to the bottom and the right wraps around to the left.
It might be easier to iterate with four loops, one each over the row and column, and then one each over the row and column of the neighborhood. Something like this should work:
int mooreNeighbors[3][3];
int nRows = 5;
int nCols = 5;
// Loop over the rows and columns of the matrix
for (int i = 0; i < nRows; ++i) {
for (int j = 0; j < nCols; ++j) {
// Loop over the cyclic Moore neighborhood
for (int mnI = 0; mnI < 3; ++mnI) {
for (int mnJ = 0; mnJ < 3; ++mnJ) {
// Sub-matrix indices
int subI = (i - mnI - 1) % nRows;
int subJ = (j - mnJ - 1) % nCols;
// Index into column-dominant matrix
int idx = subI + subJ*nRows;
mooreNeighbors[mnI][mnJ] = matrix[idx];
}
}
}
}
I haven't tried compiling this, but it should be close to correct and clear enough to correct any mistakes. Think of it as pseudo-code.
Also, I'm preferring clarity over optimality. For example, you don't have to do everything in the inner-most loop.

How to sort a vector of structure belonging to same category/set in c++

While solving a competitive coding problem I got stuck with the the following sorting scenario.
I have a vector of following structure
struct Data{
int p;
int val;
int ll;
};
Defined as :
vector<Data> a(N);
Now p field in the structure tells the set number to which val belong.
e.g if values are 1 2 3 4 5 6 7 8 9
(1,4,7) belong to group/set 3 i.e p is 3 , (2,5,8) belong to group/set 4 i.e p is 4 and (3,6,9) belong to group/set 5 i.e p is 5
i have p and val field in structure as
p as 3 4 5 3 4 5 3 4 5
val as 1 2 3 4 5 6 7 8 9
Now the problem is I have to sort the vector set wise in descending order
i.e 7 8 9 4 5 6 1 2 3
here 1 4 and 7 belong to set 3 so they are sorted in their respective places.
I tried with the selection sort as below which worked fine but it gave Time limit exceeded because of O(N^2) complexity.
for(int i=0;i<N;i++)
{
int mi=i;
Data max=a[i];
for(int j=i+1;j<N;j++)
{
if((a[i].p==a[j].p)&&(a[j].val>max.val))
{
max=a[j];
mi=j;
}
}
a[mi]=a[i];
a[i]=max;
}
Please help me find the best (time complexity) way to sort this scenario (if possible using STL sort).
Thanks in advance.
Modifying http://www.cplusplus.com/reference/algorithm/sort/, the key bit is:
#include <algorithm>
...
bool mycomparison (Data i, Data j) {
if (i.p != j.p)
return j.p < i.p;
else
return j.val < i.val;
}
...
// Sort vector a
a.std::sort( a.begin(), a.end(), mycomparison );
...
Note that reversing i and j in the return lines causes things to be in descending order.

Grid sweeps (traversal) represented with flat vector

I have a grid represented with a flat vector, that is:
-------------
| 6 | 7 | 8 |
-------------
| 3 | 4 | 5 |
-------------
| 0 | 1 | 2 |
-------------
I access the elements with the indices from 0 to grid.size()-1. I want to implement the Fast Sweeping Method. The main purpose of that method is that it does sweeps, that is, grid traversals in specific directions. For the 2D case:
Sweep 1: Right-top
for [row = 0 : nrows-1]
for [col = 0 : ncols-1] --> Result: 0 1 2 3 4 5 6 7 8
Sweep 2: Left-top
for [row = 0 : nrows-1]
for [col = ncols-1 : 0] --> Result: 2 1 0 5 4 3 8 7 6
Sweep 3: Right-bottom
for [row = nrows-1 : 0]
for [col = 0 : ncols-1] --> Result: 6 7 8 3 4 5 0 1 2
Sweep 4: Left-bottom
for [row = nrows-1 : 0]
for [col = ncols-1 : 0] --> Result: 8 7 6 5 4 3 2 1 0
And then computing idx = row*ncols + col.
This implementation is straightforward and its generalization to n dimensions as well, when just nesting for loops. However, I am working on a n-dimensional implementation and I am trying to generalize it in just 2 loops:
while (keepSweeping)
++sweep;
for (idx = init, idx == end, idx += inc)
// Traverse the grid
Computing init, end and inc is being really challenging. Also inc depends on ncols and changes dynamically. For instance, for sweep 2 inc = -1, but every ncols times inc = -1 + 2*ncols, so I achieve to go from 0 to 5.
Any help on how to do it? I am focusing firstly on the 2D case.
EDIT: I saw these threads http://www.cplusplus.com/forum/beginner/68434/ variable nested for loops that suggest to implement the loops recursively. Since I am looking for maximum performance, do you think that is a good idea?
Thank you!
Ok here is my try to answer your problem in the 2D case, using only one loop. Hopefully this is not too far from what you are looking for:
// ****** INITIALIZATION ******
int ncols = 4; // number of columns
int nrows = 3; // number of rows
boolean right = true; // direction of sweep on horizontal axis
boolean top = true; // direction of sweep on vertical axis
int counter = 0; // number of positions explored
if (right) {
colIterator = 0;
}
else {
colIterator = ncols - 1;
}
if (top) {
rowIterator = 0;
}
else {
rowIterator = nrows - 1;
}
// ****** CONTINUATION CONDITION ******
while (counter != nrows*ncols) {
// ****** DO SOMETHING ******
System.out.println(rowIterator*ncols + colIterator);
// ****** PROGRESSION PHASE ******
counter++;
// Have we completed a row?
if ((counter % ncols) == 0) {
if (top) {
// We have to move up
rowIterator++;
}
else {
// we have to move down
rowIterator--;
}
if (right) {
colIterator = 0;
}
else {
colIterator = ncols - 1;
}
}
else {
// We have not yet completed a row
if (right) {
// We have to move right
colIterator++;
}
else {
// or left
colIterator--;
}
}
}
Note: this code has been tested with Groovy.
A bit of upper-level explanation: it works with one loop because in 2D, we can find a global metric of the advancement of the work we want to do (here this metric is the counter variable) and can use the metric to determine, at each iteration of the loop, if we have completed a row (or not) by using the modulus operation.
I don't think it is mathematically possible to generalize this algorithm to upper dimensions (i.e. above 2) with only one loop, because there will be no mathematical operator that will tell us if we have finished part of the work on one given dimension and should start working on the outter dimensions (here, the modulus tells us that we have to modify the rowIterator because we have reached a border of the grid, but in dimension 3 or above 3, what would be the mathematical operator to use?).
Good luck and please post what you find, it's an interesting challenge.

StackOverflow after 27 runs

When running my Sudoku Generator, after 27 times getting stack overflow.
void start(int todel){
int number;
for (int x=0; x<9; x++) {
for (int y=0; y<9; y++) {
number = GenN(x, y);
osudoku[x][y]=number;
}
}
replace(todel);
output();
}
int GenZ(int x, int y){
int number;
bool duplication = true;
Randomize();
number = Random(9)+1;
duplication = check(number,x,y);
if (duplication==true){
return GenZ(x,y);
}
else if (duplication==false) {
return number;
}
}
I think its something with this code.
It generates things like:
758 431 629
913 267 485
642 985 317
Stack Overflow
So I get 1/3 Sudoku.
You need to add backtracking to your solution.
Consider this scenario: (which may occur at some point in your algorithm)
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 1 2 3 | ? _ _
...
Your program will just keep trying to find a value that fits at the ?, but no such value exists.
Instead, your program needs to see that no values fits, and try a different value for 3, which also won't work, then 2, then 1 in which case it should eventually put 7, 8 and 9 in the second block like:
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 7 8 9 | ? _ _
...
in which case it can continue successfully.
And this:
zahl = Random(9)+1;
won't really work as you may keep on getting values that don't fit (as in the above example). You won't know when to backtrack. It's better to loop through all 9 values. After you've looped through all 9 values, you'll know that no value fits and you'll know you must backtrack.
if duplication==true in GenZ it will call it again with the same x,y , which will again produce duplication==true? especially since I cant see you modifying "number" , so it might be at it's initialized value like 0.
if (duplication==true){
return GenZ(x,y);
}
I am not sure if that is a viable way to create a sudoku, brute-forcing might take a while no matter how you implement it, but you can probably get rid off the stackoverflow error by not using recursion and having a loop.
while (duplication){

Resources