How can I remove red rectangles from the image or convert the red rectangle color in the image to white?

2 views (last 30 days)
Merve Okan
Merve Okan on 5 Oct 2021
Edited: DGM on 8 Oct 2021
I need to remove the red rectangles from the image. Brown part should look like as a whole. How I can remove these red rectangles by using a Matlab code?
Image Analyst
Image Analyst on 7 Oct 2021
Yeah, I thought of that as a possiblility too after I posted my answer. Precise phrasing of the problem can prevent people from wasting their time. If that is the case, then he should attach/post the original underlying image. The actual image, not a cell phone image of the screen, and not the image with stuff like grids and green lines in the overlay.

Sign in to comment.

Answers (2)

DGM on 5 Oct 2021
Edited: DGM on 8 Oct 2021
You could try to bludgeon the image with a median filter, but that's not going to be too great:
A = imread('');
for c = 1:size(A,3)
% do this in a loop because a bunch of IPT tools can't do RGB fnar
B(:,:,c) = medfilt2(A(:,:,c),[20 20]);
Alternatively, you could try to select the grid features and get rid of them by inpainting.
% build a mask
fs = 30;
Ag = imflatfield(rgb2gray(A),100);
m = (medfilt2(Ag,[fs fs])-Ag)>5;
m = imdilate(m,ones(3));
% remove masked content and fill by interpolation
for c = 1:size(A,3)
% do this in a loop because a bunch of IPT tools can't do RGB fnar
B(:,:,c) = regionfill(A(:,:,c),m);
%B(:,:,c) = medfilt2(B(:,:,c),[5 5]); % if you want
That's not as blurry, but it's not perfect either. There are a number of things that can be tweaked that might make it marginally better, but I don't know how much better it can be. There are probably other, more complicated things that can be done too. Bear in mind that you're working with a relatively small JPG of all things.
This is a very crude example of approximating the annotated edge segment. The results are accordingly poor. This makes use of MIMT tools, as I'm not going to bother trying to do this with IPT-only tools. If desired, MIMT can be found on the File Exchange.
D = imflatfield(imlnc(im2double(B)),100); % imlnc() is MIMT-only
De = min(10*edgemap(D),1); % edgemap() is MIMT-only
T = [0.982 0.179; 0.359 1; 0.207 1]; % threshold values
Dl = rgb2hsv(De);
mask = (Dl(:,:,1)>=T(1,1) | Dl(:,:,1)<=T(1,2)) ...
& Dl(:,:,2)>=T(2,1) & Dl(:,:,2)<=T(2,2) ...
& Dl(:,:,3)>=T(3,1) & Dl(:,:,3)<=T(3,2);
mask = imclose(mask,strel('disk',5));
mask = bwareafilt(mask,1);
mask = morphnhood(morphnhood(mask,'skel',100),'prune',20);
% morphnhood is MIMT-only
As I mentioned, it's not very good. Trying to find the breakpoint between the shoe+shadow looking object and the diagonal line object is quite ambiguous.
Could this be done by simple color-based segmentation of the filtered image? Yes. Feel free to have fun with that. I managed to get an equally crude and problematic mask by subdividing the image into regions and creating multiple masks. I don't consider my attempt of that method to be even remotely robust or practical for this image, so I'm omitting it. Someone else might have more luck.
Ultimately, I have to ask what the goal is here. A lot of the times people are intent on finding a way to segment an image or find an edge, they actually only have one or two images to process. If that's the case, it's likely going to be much faster and much more accurate to just do it by hand (e.g. using interactive ROI generation tools). Trying to make this process automatic and robust for images of this quality is going to be an exercise in frustration. Of course, I can only guess, since I haven't seen any other images (if there are others).
ROI Tools:
Using Inkscape (external) to fit splines to image features:
Here's a quick example of using a polyline ROI:
clf % get rid of prior subplots
h = drawpolyline(gca);
mask = createMask(h);
Here's an example of using external tools to fit a spline:
% start by exporting C and opening it in inkscape, draw path, save as SVG
fname = 'C.svg';
% spline discretization parameter [0 1]
coarseness = 0.01;
% get image geometry (needed to locate spline)
str = fileread(fname);
str = regexp(str,'((?<=<image)(.*?)(?=\/>))','match');
pbx = regexp(str,'((?<=x=")(.*?)(?="))','match');
pby = regexp(str,'((?<=y=")(.*?)(?="))','match');
pbw = regexp(str,'((?<=width=")(.*?)(?="))','match');
pbh = regexp(str,'((?<=height=")(.*?)(?="))','match');
pbrect = [str2double(pbx{1}{1}) str2double(pby{1}{1}) ...
str2double(pbw{1}{1}) str2double(pbh{1}{1})];
% get coordinates representing the curve
S = loadsvg(fname,coarseness,false);
x = S{1}(:,1); % assuming the first path is the correct one
y = S{1}(:,2);
% rescale to fit original image geometry
x = size(C,2)*(x-pbrect(1))/pbrect(3);
y = size(C,1)*(y-pbrect(2))/pbrect(4);
h = images.roi.Polyline(gca);
h.Position = [x y];
mask = createMask(h);
I attached the SVG for this example for sake of clarity. The function loadsvg() can be found here:
Mind you, if you don't need the x-y data, this method can be simplified dramatically.

Image Analyst
Image Analyst on 7 Oct 2021
Merve, you can use the color thresholder to detect the green line, which appears to be your real question (not how to find red rectangles):
% Demo by Image Analyst.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
% Read in image. This is a horrible image. NEVER use JPG format for image analysis. Use PNG, TIFF, or BMP instead.
folder = [];
baseFileName = 'image.jpeg';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display the image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
caption = sprintf('Original RGB Image : "%s"\n%d rows by %d columns', baseFileName, rows, columns);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
hFig1.Name = 'Demo by Image Analyst';
% Find the green line:
[mask, maskedRGBImage] = createMask(rgbImage);
% Display the mask image.
subplot(2, 2, 2);
imshow(mask, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Display the masked image.
subplot(2, 2, 3);
imshow(maskedRGBImage, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
title('Masked Image', 'FontSize', fontSize, 'Interpreter', 'None');
function [BW,maskedRGBImage] = createMask(RGB)
%createMask Threshold RGB image using auto-generated code from colorThresholder app.
% [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
% auto-generated code from the colorThresholder app. The colorspace and
% range for each channel of the colorspace were set within the app. The
% segmentation mask is returned in BW, and a composite of the mask and
% original RGB images is returned in maskedRGBImage.
% Auto-generated by colorThresholder app on 07-Oct-2021
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.165;
channel1Max = 0.460;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.297;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.000;
channel3Max = 1.000;
% Create mask based on chosen histogram thresholds
sliderBW = (I(:,:,1) >= channel1Min ) & (I(:,:,1) <= channel1Max) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
% Initialize output masked image based on input image.
maskedRGBImage = RGB;
% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by