dll - Matlab : convert a uint8 matrix (made of 0 and 1) to export as binary data -


my problem :

i have 1920x1080 uint8 matrix made of zeros , ones in matlab. let's call "image". want exporting image binary, meaning each byte of output should contain information of 8 pixels. in short : want 1bit per pixel.

if understood well, can't convert binary in matlab "logical(...)" function because logicals still stored 8bits in memory (although value can 0 or 1 of course).

why need ?

i want export image through ".dll" accepts image in specific format (for faster transfer usb device).

the format of output :

here ".dll" expecting : (1 byte = 8 consecutive bits)

  • the image reads left right, top bottom (usual convention)
  • every byte of data represents 8 pixels, e.g.
    • (1st byte) = [px8|px7|...|px1]
    • (2nd byte) = [px16|px15|...|px9]
    • and on.
  • note every line of image has 1920 pixels (which can divided 8, 1920/8=240) there 240 bytes per line of image

my question :

how should reorganize data ? guess depends on how matlab stores data in memory (and sends ".dll")? have no idea that...

here code use if no memory tricks expected. idea take every 8 pixels , build 8bit value them in correct order, e.g. these pixel values (1 0 0 0 0 0 1 0) become 65 (expressed in decimal). send new matrix ".dll" , hope works.

finalimage=zeros(1920,240); % 240 = number of bytes per line myrow=1:1080     mybyte=1:240          currentbyte=0;         mybit=0:7             currentbyte=currentbyte + 2^(7-mybit) * image(myrow, 1 + 8*(mybyte-1) + mybit );         end         finalimage(myrow, mybyte) = currentbyte;     end end 

solution :

with of divakar, forgot loops , preferred simple code:

% convert every 8 pixels (values 0 or 1) in row 1 single pixel (value 0 255) % (bi2de option used : "left significant bit" in case) % (make sure width of image multiple of 8)  vect=bi2de(reshape(input_img',8,[])','left-msb'); img=reshape(vect,img_width/8,[])'; 

this solution might helpfull else, 1 day or !

assuming input_image input binary matrix , output_dll_filepath path output dll file, may try cell-array approach -

code

%// convert 8-bit data [m,n] = size(input_image) cell1 = mat2cell(input_image,ones(1,m),8.*ones(1,n/8)) output_data = cellfun(@(x) bin2dec(num2str(fliplr(x),'%1d')),cell1); output_data = reshape(output_data',[],1)  %// write 8-bit data dll file fid = fopen(output_dll_filepath , 'w'); fwrite(fid, output_data, 'uint8'); fclose(fid); 

or use -

output_data = bin2dec(fliplr(num2str(reshape(input_image',8,[])','%1d'))) 

and use write 8-bit data dll file used earlier was.


or -

fid = fopen(output_dll_filepath , 'w'); fwrite(fid, reshape(input_image',8,[]), 'ubit1'); fclose(fid); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -