0

I need to draw the closest thing to a major diagonal on a picture(irregular matrix). I already know that for a regular one the format is the following:

for (i = 0; i < row; i++) {
    for (j = 0; j < column; j++) {
        if(i==j){
             matrix[row][column] = color_of_diagonal;
        }
    }
  }

But adapt that to a rectangle is obiviously different... I saw some note algorithm but i didn't understood very well their work. Someone could help me?

P.S.: It would be cool if it could be explained a way to draw multiple "diagonal" lines on the image too, but that's not the main problem.

  • 2
    You should look at the [tag:bresenham] algorithm. – 1201ProgramAlarm Oct 27 '20 at 19:00
  • The code you posted fills the entire image with a color. Regardless, you're looking for bresenham's stepping algorithm. – Botje Oct 27 '20 at 19:01
  • Botje you are right i'll fix – SaltyGiampy Oct 27 '20 at 19:04
  • Are you sure you want to implement graphics primitives? Do you use any graphics subsystem that might provide that? – Vlad Feinstein Oct 27 '20 at 19:06
  • Using two levels of loops for your square example looks like over complicated, and of course inefficient. `for (i = 0; i < row; i++) matrix[i][i] = color_of_diagonal;` would do. In addition, I suppose it is a typo to use `row` and `column` instead of `i` and `j` when indexing the matrix. – prapin Oct 27 '20 at 19:09
  • prapin i need to operate on all the matrix so i'll use the full iteration anyway, but that's a nice advice. Thanks! – SaltyGiampy Oct 27 '20 at 19:11
  • [DDA](https://stackoverflow.com/a/24682318/2521214) is much simpler and even faster than Bresenham these days ...anyway what you want to google is `line rasterization algorithm` which will lead you to DDA and Bresenham anyway... – Spektre Nov 06 '20 at 08:59

1 Answers1

1

First of all, can you use a library like OpenCV? If so, then something like

# you need to convert this python code to c++. Should not be that difficult
r, c = matrix.shape[:2]
cv2.line(matrix,(0,0), (c-1, r-1), color= color_of_diagonal) 

Otherwise, you need to do either do some interpolation or have something like a jaggy line.

# c++ code here, I am rusty a bit (we know that matrix is r rows, c cols.)
aspect = (float)c/r
for (int i = 0; i < r; i++)
    matrix[i][(int)(aspect*i)] = color_of_diagonal

So, this code finds the corresponding point in the diagonal line in each row. I wrote the same code in python and here is the result

r, c = 100, 200
mat = np.zeros((r, c))
aspect = c/r
for i in range(10):
    mat[i, int(i*aspect)]=255
import matplotlib.pyplot as plt
plt.imshow(mat)
plt.show()

image

Another image when the image is 100*137 (kinda arbitrary)

image2

Also, notice that the complexity is pretty low, it is O(r) where r is the number of rows whereas your code will O(r*c)

smttsp
  • 4,011
  • 3
  • 33
  • 62