Please I want to modify that code for run length to work on gray scale image

2 views (last 30 days)
------------------------------------------------------------------------
I want to modify that code to make it work on grayscale image not binary image can anyone help me
----------------------------------------------------------------------------------
function out=rle(image)
%
% RLE(IMAGE) produces a vector containing the run-length encoding of
% IMAGE, which should be a binary image. The image is set out as a long
% row, and the conde contains the number of zeros, followed by the number
% of ones, alternating.
%
% Example:
%
% rle([1 1 1 0 0;0 0 1 1 1;1 1 0 0 0])
%
% ans =
%
% 03453
%
level = graythresh(image);
BW = im2bw(image, level);
L=prod(size(BW));
im=reshape(BW',1,L);
x=1;
out=[];
while L ~= 0,
temp=min(find(im == x));
if isempty(temp),
out=[out L];
break
end;
out=[out temp-1];
x=1-x;
im=im(temp:L);
L=L-temp+1;
end;
------------------------------------------------------------------------
Please I want to modify that code to make it work on grayscale image not binary image can anyone help me

Accepted Answer

Jan
Jan on 24 Jun 2017
Edited: Jan on 26 Jun 2017
There is no Run Length defined for matrices, but only for vectors. Even your code converts the input image to a vector at first in:
im=reshape(BW',1,L);
So simply call FEX: RunLength by:
img = rand(640, 480); % Example image data
imgV = reshape(img.', 1, []); % Convert to vector
[B, N] = RunLength(imgV);
If you do not have a compiler installed or speed doesn't matter, user the included RunLength_M. Or cut the needed lines only:
function [b, n] = rle(ImageMatrix)
x = reshape(ImageMatrix.', [], 1);
d = [true; diff(x) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
k = find([d', true]); % Indices of changes
n = diff(k); % Number of repetitions
end
By the way: Your code is not a Run Length Encoder. The example from the help section
rle([1 1 1 0 0;0 0 1 1 1;1 1 0 0 0])
does not reply 03453, but only 3. This means that the posted code does not work. In consequence I cannot replace it directly by a method working with gray scale images. The commands graythresh and im2bw seems, like the code should work with grey scale images already.
  7 Comments
Jan
Jan on 26 Jun 2017
Yes, this is possible. If each pixel is repeated twice, the compression is e.g. 1.0. For an image without repetitions, the output is twice as large. Therefore images are not compressed by pure RLE methods, as you know.

Sign in to comment.

More Answers (0)

Categories

Find more on Denoising and Compression in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!