wildcolor wildcolor - 4 months ago 15
Python Question

how to find the black region in near the edge

I have an image like below. It has black border/regions in the top and right side of the image. I want to be able to find these regions like shown in the 2nd images. Note these regions should be always streight (ie rectangle shaped). I want to be able to do this using 'image processing with code not with photoshop' (such as matlab, c# or opencv).

 Input image

 output image

I am very new to 'image process'. I have tried to find all the pionts that have (0,0,0) rgb values. But because there are so many of these black values in the noise part (and any other places in the images). My result region also contains these unwanted region....

---------- Edit ---------------
Thanks for all the comments/answers. However, I have lots of these images. Some of them are rotated, which is a bit more difficult to deal with. I have just uploaded one as shown below.

enter image description here

Answer
color_img = imread('0k4Kh.jpg');
img = rgb2gray(color_img);
[x, y] = size(img);

for i = 1:x
    if length(find(img(i, :))) ~= 0
        lastmarginalrow = i-1;
        break;
    end
end

for ii = y:-1:1
    if length(find(img(:, ii))) ~= 0
        lastmarginalcol = ii-1;
        break;
    end
end

figure;
fig = imshow(color_img);
h = impoly(gca, [0,x; lastmarginalcol,x; lastmarginalcol,lastmarginalrow; 0,lastmarginalrow]);
api = iptgetapi(h);
api.setColor('red');
saveas(fig, 'test.jpg');
close all;

Here is the implementation in MATLAB. Find zeros column and zeros row and draw a border using them.

For Rotated Images (should work for non-rotated also)

color_img = imread('N6vK9.png');
img = rgb2gray(color_img);
[x, y] = size(img);

verts = [];
% traversing through all columns
for i = 1:y
    % find all non-zero pixels in each column
    nonzeros = find(img(:,i));
    % if all pixels are black in a column, below if condition will skip
    if length(nonzeros) ~= 0
        % if there is atleast one non-zero pixel, not that co-oridinate/positions in matrix by appending
        verts = [i, nonzeros(1); verts];
    end
end

figure;
fig = imshow(color_img);
% polygon based on first and last vertix/co-ordinate of found non-zero co-ordinates
% Assumed that it was slanted straight line, used last and first co-ordinate. If it is curvy border, anyways we have all veritices/co-ordinates of first non-zero pixel in all columns.
h = impoly(gca, [verts(1,:); verts(length(verts), :); 1,x; verts(1),x]);
api = iptgetapi(h);
api.setColor('red');
saveas(fig, 'test.jpg');
close all;

enter image description here