Conversion from binary to decimal number in MATLAB

坚强是说给别人听的谎言 提交于 2020-01-07 08:31:54

问题


I have a problem in converting the binary to decimal (it seems very lengthy).

%% Read

clear all;
close all;
clc;
I=imread('test.png');
imshow(I);

%% Crop
I2 = imcrop(I);
figure, imshow(I2)
w=size(I2,1);
h=size(I2,2);
%% LBP
for i=2:w-1
    for j=2:h-1
        J0=I2(i,j);
        I3(i-1,j-1)=I2(i-1,j-1)>J0;
        I3(i-1,j)=I2(i-1,j)>J0;
        I3(i-1,j+1)=I2(i-1,j+1)>J0; 
        I3(i,j+1)=I2(i,j+1)>J0;
        I3(i+1,j+1)=I2(i+1,j+1)>J0; 
        I3(i+1,j)=I2(i+1,j)>J0; 
        I3(i+1,j-1)=I2(i+1,j-1)>J0; 
        I3(i,j-1)=I2(i,j-1)>J0;
        LBP(i,j)=I3(i-1,j-1)*2^8+I3(i-1,j)*2^7+I3(i-1,j+1)*2^6+I3(i,j+1)*2^5+I3(i+1,j+1)*2^4+I3(i+1,j)*2^3+I3(i+1,j-1)*2^2+I3(i,j-1)*2^1;
    end
end
figure,imshow(I3)
figure,imhist(LBP)

Is it possible to change this line

LBP(i,j)=I3(i-1,j-1)*2^8+I3(i-1,j)*2^7+I3(i-1,j+1)*2^6+I3(i,j+1)*2^5+I3(i+1,j+1)*2^4+I3(i+1,j)*2^3+I3(i+1,j-1)*2^2+I3(i,j-1)*2^1;

to something shorter?


回答1:


Option 1:

One way to simplify what you're doing is to first create a 3-by-3 matrix of scale factors (i.e. powers of two) and initialize it before your loops:

scale = 2.^[8 7 6; 1 -inf 5; 2 3 4];

Then you can replace everything inside your loop with these vectorized operations:

temp = (I2(i-1:i+1,j-1:j+1) > I2(i,j)).*scale;
LBP(i,j) = sum(temp(:));

Option 2:

Alternatively, I believe you can remove both of your loops entirely and replace them with this single call to NLFILTER to get your matrix LBP:

LBP = nlfilter(I2,[3 3],@(x) sum((x(:) > x(5)).*scale(:)));



回答2:


I'm not exactly sure what you're doing there, but does bin2dec do what you want?




回答3:


I'm adding another solution with the COLFILT function.

It involves placing all sliding window into columns of a matrix, which we process using a custom function, then it rearranges the result into the original matrix. Internally it uses the IM2COL and COL2IM functions.

Here is an example:

I = imread('coins.png');
fun = @(b) sum( bsxfun(@times, 2.^(8:-1:1)', ...
           bsxfun(@gt, b([1 4 7 8 9 6 3 2],:), b(5,:))) );
II = colfilt(I, [3 3], 'sliding', fun);
imshow(II, [])

With comparison to @gnovice's second answer, read this tip from the NLFILTER documentation:

nlfilter can take a long time to process large images. In some cases, the colfilt function can perform the same operation much faster.



来源:https://stackoverflow.com/questions/7390315/conversion-from-binary-to-decimal-number-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!