0

I have Matlab code for run length encoding and I want to make code for decoding. Please can anyone help me in making the decoder for this code?

The encoder is as the following:

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
end
Wolfie
  • 27,562
  • 7
  • 28
  • 55
  • 2
    Refrain from asking questions where you seek the solution. Rather ask how to get to the solution and show your own inputs in getting there. – Nissim R Jun 19 '17 at 21:04
  • 1
    @advise also clearly formatted code is an important skill when you're trying to communicate in code (or at the very least, shows you put some effort into helping others read it). Pay attention to this! :) – Tasos Papastylianou Jun 19 '17 at 21:12

2 Answers2

2

Matlab has a built-in function for run-length decoding, namely repelem (starting at R2015a). You feed it with a vector containing the original values (0 and 1 in your case) and a vector containing the run-lengths.

Let x = [0 3 4 5 3] be the input. Then,

y = repelem(mod(0:numel(x)-1, 2), x)

gives

y =
     1     1     1     0     0     0     0     1     1     1     1     1     0     0     0

which is the orinal image in linearized form as per your encoding function.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    +1 That's a nice answer. But I agree with Nissim's comment, it'd be nice if the OP showed some effort in understanding what the problem even is before presented with such a slick solution. – Tasos Papastylianou Jun 19 '17 at 21:08
  • @TasosPapastylianou Totally agree. But the answer was so simple... :-) And when there's a built-in function, it's better to use it than to develop your own (unless for practice, of course) – Luis Mendo Jun 19 '17 at 21:09
  • @Luis Mendo It is but please can you help me to make this code for grayscale image not for binary image – advise20023 Jun 23 '17 at 14:14
0

There is also a shorter but more complex solution to this problem. You pass the gray value and rows of the gray level matrix to the function RLE and it gives you the answer.

function rle = RLE(gray_value, image_rows)
for i =1:image_rows
    diF = diff([gray_value(i,1)-1, gray_value(i,:)]) ;
    k = diff([find(diF), numel(gray_value(i,:))+1]);
    rle=[gray_value(i,find(diF));k] ;
end
end
Pouyan
  • 363
  • 5
  • 22