Search code examples
imagematlabimage-processinglinehough-transform

Change pixel values on a line in MATLAB


I wish to set values on a line whose endpoints are returned by the hough transforms to zero. I have written the following code snippet

imshow(img); 
hold on
img_black = img;

for k = 1:length(lines)

    xy = [lines(k).point1; lines(k).point2];  %line end points
    [x, y] = bresenham(xy(1,1),xy(1,2),xy(2,1),xy(2,2));   %returns all points on the line

    for i = 1:length(x)
        plot(x(i),y(i),'*');   %to plot individual pixels on line itself
        img_black(x(i),y(i),:) = [0,0,0];    %set rgb values to zero
    end   
end

Although the points plotted on the image below are as expected

The image where the corresponding pixel values are being set to zero is not as expected.

enter image description here

What is happening here?


Solution

  • It looks like you have mixed up x and y with rows and columns.

    img_black(x(i), y(i),:)
    

    Should be

    img_black(y(i), x(i),:);
    

    This is because the first dimension of img_black is rows (y) and the second dimension is columns (x).

    The resulting image looks like it does because your lines go the wrong way and (sometimes) go outside the bounds of the original image, but MATLAB gladly expands your image (with zeros) and sets the values that you request, hence all the black pixels on the right.

    NOTE: This switching back and forth between row, column and x,y is common throughout MATLAB's built-in functions and you should always be careful to note what the output is. A class example is meshgrid vs ndgrid outputs.