Convert each row of a grayscale image from decimal to binary and store it in an array

1 view (last 30 days)
I have the following code which pops up an error 'Unable to perform assignment because the indices on the left side are not compatible with the size of the right
side.' along with 'Error in input_image (line 13) in_signal(1,(((i-1)*n*8)+1):(i*n*8)) = in_img_bin;'
clc;
close all;
%256 x 256 image in grayscale
in_img = imread('image.bmp');
%image to binary code
in_signal= [];
n=256; %image size
for i= 1:n
%convert each row of image from decimal to binary
[in_img_bin] = dec2bin(double(in_img(i,:)));
%save into rows of size equal of 2048 elements => 256*8
%e.g.,1-2048, 2049-4096, ...
in_signal(1,(((i-1)*n*8)+1):(i*n*8)) = in_img_bin;
end
%output->in_signal
%____________________________________________________
out_signal = in_signal;
% binary code -> image %
% input-> out_signal
out_img =uint8(zeros(n,n));
[out_img_d] = bin2dec(out_signal);
out_img = uint8(out_img_d);
figure(1)
imshow(in_img)
figure(2)
imshow(out_img)
%__________________________________________________________________________

Answers (1)

Mark Sherstan
Mark Sherstan on 15 Dec 2018
Are you able to use built in functions?
I = imread('image.png');
BW = imbinarize(rgb2gray(I));
Otherwise the error is coming from the conversion to binary. The matrix is now made of characters that are n x 8 and not numbers of n x 1 so indices arent maching up. Store the data in a cell aray and do the conversion at the end. For example:
for i = 1:n
in_signal{ii} = dec2bin(double(I(ii,:)));
end
I dont full understand your conversions of going from dec2bin then bin2dec so I will leave that last part for you but hopefully this puts you in the right direction.
  1 Comment
Image Analyst
Image Analyst on 15 Dec 2018
I don't understand why he's using dec2bin() to convert the gray level value into a string either. A binary string, like you get with dec2bin(), is not the same as a binary image, which is of type logical, not char. They're totally different.
Maybe he'll explains what he really wants. Often a user says "How do I do X?" and we tell them and then they say "it doesn't work" for what they want to do later in the code. Then we ask "what do you really want to do" and they say "I want to do Z", and we reply "well if you want Z, you don't want to do X, like you asked, you really should do Y."
This could well be the situation here.

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!