-
2006-09-06
用matlab读取16位灰度bmp图像(续) - [Matlab]
昨天导师让我读取一14位灰度的bmp图像。因为我原来是在matlab下整过14位灰度bmp图像的。我用原来写的matlab程序来读取这种图像。但是与正确的数据总是偏差一点。究竟是哪里出了问题。费了好大的劲还是没找到原因。是不是我的原理有问题?对了,可以看一下matlab是如何读取16位的bmp图像的。因为matlab在读取完16位bmp图像之后还得将其转化为RGB三分量。如果知道了matlab是如何将16位数据转化为RGB三分量的话,将RGB三分量复原为16位的数据也就不复杂了。经过长时间的仔细查找,终于在readbmpdata.m这个文件中找到了matlab将16位数据转化为RGB三分量的那段代码。代码如下:
RGB(1:abs(height), 1:width, 1) = uint8(bitslice(X,11,15));
RGB(:,:,2) = uint8(bitslice(X,6,10));
RGB(:,:,3) = uint8(bitslice(X,1,5));%Scale data for display
RGB = bitor(bitshift(RGB,3),bitshift(RGB,-2));原来RGB三分量是各自从16位的数据X中取其中的5位。将这5位的数据左移3位与这5位数据右移2位相或,最终得到了8位的数据。如此的话,将RGB三分量复原成16位的数据就不困难了。
原来的程序是这样的:
function b=read16graybmp(filename)
if(nargin~=1)
error('Need 1 parameters!');
end;0
i=0:2^5-1;index5=floor(i*255.99/(2^5-1));%for 5bits
value5(index5 1)=0:2^5-1;
a=imread(filename);
b1=value5(a(:,:,1) 1);
b2=value5(a(:,:,2) 1);
b3=value5(a(:,:,3) 1);
b=bitshift(uint16(b1),10) bitshift(uint16(b2),5) uint16(b3);
如果按照matlab将16位数据转化成RGB三分量的原理的话,程序可以是这样:
function b=read16graybmp(filename)
if(nargin~=1)
error('Need 1 parameters!');
end;0
i=0:2^5-1;index5=floor(i*255.99/(2^5-1));%for 5bits
value5(index5 1)=0:2^5-1;
a=imread(filename);
b1=bitshift(a(:,:,1),-3);
b2=bitshift(a(:,:,2),-3);
b3=bitshift(a(:,:,3),-3);
b=bitshift(uint16(b1),10) bitshift(uint16(b2),5) uint16(b3);
但是仔细想想,两者的原理是相类似的。如果在运行
i=0:2^5-1;index5=floor(i*255.99/(2^5-1));
i8=uint8(i);index55=bitor(bitshift(i8,3),bitshift(i8,-2));
a=index5==index55;find(a==0)
结果显示index5与index55是一样的。但原来写的程序读出来的数据有的就是有偏差,究竟是怎么回事呢。费了好大的劲才找到问题。原来a=imread(filename);执行后,a的类型是uint8,如果a是255的话,那么加1等于0而不是256,问题就出在这里。于是,我们可以将原来的程序稍微改动一下就可以了。
function b=read16graybmp(filename)
if(nargin~=1)
error('Need 1 parameters!');
end;0
i=0:2^5-1;index5=floor(i*255.99/(2^5-1));%for 5bits
value5(index5 1)=0:2^5-1;
a=double(imread(filename));
b1=value5(a(:,:,1) 1);
b2=value5(a(:,:,2) 1);
b3=value5(a(:,:,3) 1);
b=bitshift(uint16(b1),10) bitshift(uint16(b2),5) uint16(b3); -
2006-03-31
利用低通滤波实现图像的插值放大 - [Matlab]
前些时候去上《软件无线电》时,听老师讲信号插值的原理:在相邻两个信号间插入N-1个零,然后信号通过低通滤波器,原先插入的零的位置自动替换为适当的插值,觉得甚是奇妙。如果将其应用于图像的插值,就不用再一个个地来计算所在位置的插值了。经过几天的试验,终于成功了。大体是设要将原图像放大N倍,则在原图像数据的相邻两个像素插入N-1个零,将插值后的图像进行FFT2变换,在频域对数据进行截取,将高频部分置为1(或是0),再进行IFFT2变换,如此图像就已经插值放大的,图像质量跟还不错。
参考程序如下:
%a function to magnify the image using the lowpass filter.
% function cout=magnif(filestr,x,y)
% filestr: the image filename string
% x:the times magnify in the row direction,integer>=1
% y:the times magnify in the column direction,integer>=1;
%designed by darnshong,chenzushang@sina.com
%March 31,2006
function cout=magnif(filestr,x,y)
a=imread(filestr);
timesx=round(x);%x;
timesy=round(y);%y;
b=a(:,:,1);
xy=size(b);
sy=xy(1);
sx=xy(2);
c2=zeros(sy*timesy,sx*timesx);
n=1:sy;
m=1:sx;
c2(n*timesy,m*timesx)=b(n,m);
if(timesx>1)
for i=timesy:timesy:(sy*timesy),
fc=fft(c2(i,:));
fc((ceil((sx+1)/2)):(timesx*sx-ceil((sx+1)/2)+1))=0;
c2(i,:)=abs(ifft(fc));
end,
end,
if(timesy>1)
for j=1:(sx*timesx),
fc=fft(c2(:,j));
fc((ceil((sy+1)/2)):(timesy*sy-ceil((sy+1)/2)+1))=0;
c2(:,j)=abs(ifft(fc));
end
end,
c2=c2*timesx*timesy;
% minc=min(min(c2));
% maxc=max(max(c2));
% cout=uint8(256/(maxc-minc).*(c2-minc));
cout=uint8(c2);
%imshow(c2); -
2006-02-21
利用matlab获取TTF字体的字模信息(font2pic,font2bmp,ttf2pic,ttf2bmp) - [Matlab]
//matlab mex file to convert font characters to image
//author:darnshong http://darnshong.52blog.net
//date:2006,2
//compile to use >> mex font2pic.c user32.lib gdi32.lib
//declaration: a=font2pic(iBits,iHeight,iAngle,iBold,bItalic,pstrFontName,chartemp);
// iBits:double the font chararter's resolution 1,2,3,4
// iHeight:double the font character's height
// iAngle:double the font character's angle
// iBold: double the font character's weight
// bItalic: boolean be italic or not
// pstrFontName:char array the fontname.
//You can use "a=enumfont;" to get all the right fontnames;
// chartemp: char the font character
//e.g.:a=font2pic(2,695,0,300,0,'华文行楷','尚');
//usage: >>a=font2pic(2,695,0,300,0,'华文行楷','尚');
// >>imshow(a)#include <windows.h>
#include <string.h>
#include <tchar.h>
#include "mex.h"
int BITSTABLE[]={2,5,17,65};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int iBits,iHeight,iAngle,iBold,charLineW,nDims[2],i,j,k,recchar;
UINT uchar;
bool bItalic,*pbool;
BYTE chartemp[3];
char *pBuf=NULL,*pchar,pstrFontName[100];
mxChar *cShowChar;
MAT2 mmat2={0,1,0,0,0,0,0,1};
GLYPHMETRICS glpm;
HFONT hfont,hold;
HDC hdc;
DWORD nLen,nLentemp;
if(nrhs!=7)
mexErrMsgTxt("The number of input arguments must be 7");
iBits=(int)*(double*)mxGetData(prhs[0]);
iHeight=(int)*(double*)mxGetData(prhs[1]);
iAngle=(int)*(double*)mxGetData(prhs[2]);
iBold=(int)*(double*)mxGetData(prhs[3]);
bItalic=(bool)*(double*)mxGetData(prhs[4]);
mxGetString(prhs[5],pstrFontName,100);
mxGetString(prhs[6],chartemp,3);
if(iBits<1 || iBits>4)
mexErrMsgTxt("The iBits must be an integer between 1 and 4.\n");
if(chartemp[0]<128)
{
uchar=chartemp[0];
}
else
{
//mexPrintf("the char num is %d\n",chartemp[0]);
uchar=chartemp[0];
uchar=uchar<<8;
//mexPrintf("the char num is %d\n",uchar);
uchar+=chartemp[1];
//mexPrintf("the char num is %d\n",uchar);
}
//mexPrintf("iBits:%d;iHeight:%d;iAngle:%d;iBold:%d;iItalic:%d;FontName:%s;Char:%d\n",iBits,iHeight,iAngle,iBold,bItalic,pstrFontName,uchar);
//printf("The font name is %s\n",pstrFontName);
hfont=CreateFont(iHeight,0,iAngle,0,iBold,bItalic,0,0,DEFAULT_CHARSET,OUT_CHARACTER_PRECIS,CLIP_CHARACTER_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH|FF_DONTCARE,pstrFontName);
if(hfont==NULL)
{
mexErrMsgTxt("Fail to create the font!\n");
}
hdc=GetWindowDC(NULL);
hold=SelectObject(hdc,hfont);
if(iBits==1)
nLen=GetGlyphOutline(hdc,uchar,iBits,&glpm,0,NULL,&mmat2);
else
nLen=GetGlyphOutline(hdc,uchar,iBits+2,&glpm,0,NULL,&mmat2);
//GGO_BITMAP 1
// GGO_GRAY2_BITMAP 4
// GGO_GRAY4_BITMAP 5
//GGO_GRAY8_BITMAP 6
if(nLen!=GDI_ERROR)
{
if(pBuf!=NULL)
free(pBuf);
if(nLen<0)
mexErrMsgTxt("the malloc memory'size can't be negative!\n");
pBuf=(char*)mxMalloc(nLen);
if(pBuf==NULL)
{
mexErrMsgTxt("Fail to malloc the memory!\n");
}
if(iBits==1)
{
nLentemp=GetGlyphOutline(hdc,uchar,iBits,&glpm,nLen,pBuf,&mmat2);
if(nLentemp!=nLen)
{
mexPrintf("The font size is too big!\n");
exit(-1);
}
charLineW=(glpm.gmBlackBoxX/32+(glpm.gmBlackBoxX%32==0?0:1))*4;
//mexPrintf("charLine:%d,X:%d; Y:%d\n",charLineW,glpm.gmBlackBoxX,glpm.gmBlackBoxY);
nDims[0]=glpm.gmBlackBoxY;
nDims[1]=glpm.gmBlackBoxX;
if(nDims[0]<=0 || nDims[1]<=0)
{
mexErrMsgTxt("return error matrix!\n ");
}
plhs[0]=mxCreateNumericArray(2,nDims,mxLOGICAL_CLASS,mxREAL);
pbool=(bool*)mxGetData(plhs[0]);
for(j=0;j<glpm.gmBlackBoxY;j++)
for(i=0;i<glpm.gmBlackBoxX/8;i++)
for(k=0;k<8;k++)
{
pbool[(8-k+i*8)*glpm.gmBlackBoxY+j]=!((pBuf[j*charLineW+i]&1<<k)>>k);
}
}
else
{
nLentemp=GetGlyphOutline(hdc,uchar,iBits+2,&glpm,nLen,pBuf,&mmat2);
if(nLentemp!=nLen)
{
//mexPrintf("The font size is too big!\n");
exit(-1);
}
charLineW=(glpm.gmBlackBoxX/4+(glpm.gmBlackBoxX%4==0?0:1))*4;
// mexPrintf("charLine:%d,X:%d; Y:%d\n",charLineW,glpm.gmBlackBoxX,glpm.gmBlackBoxY);
nDims[0]=glpm.gmBlackBoxY;
nDims[1]=glpm.gmBlackBoxX;
if(nDims[0]<=0 || nDims[1]<=0)
{
mexErrMsgTxt("return error matrix!\n ");
}
plhs[0]=mxCreateNumericArray(2,nDims,mxUINT8_CLASS,mxREAL);
pchar=(BYTE *)mxGetData(plhs[0]);
for(j=0;j<glpm.gmBlackBoxY;j++)
for(i=0;i<glpm.gmBlackBoxX;i++)
pchar[i*glpm.gmBlackBoxY+j]=(BYTE)(255.0-pBuf[j*charLineW+i]*255.0f/(BITSTABLE[iBits-1]-1));
}
mxFree(pBuf);
}
else
{
plhs[0]=NULL;
//mexPrintf("nLen is %d,The font size is too big!\n",nLen);
mexErrMsgTxt("Fail to select the font!\n");
}
SelectObject(hdc,hold);
DeleteObject(hfont);
ReleaseDC(GetDesktopWindow(),hdc);
} -
2005-12-24
用matlab枚举操作系统安装的TTF字体(window) - [Matlab]
//matlab mex file to enum the system font(window)
//compile to use >>mex eunmfont.c user32.lib gdi32.lib
//usage: >>a=enumfont();
// >>a
// designed by darnshong chenzushang@sina.com http://darnshong.52blog.net
//2005,12,24
#include <windows.h>
#include <string.h>
#include <tchar.h>
#include "mex.h"_TCHAR *pchar[500];
_TCHAR temp[200];
int strnum=0;
int strleng;
int CALLBACK MyEnumFontProc(ENUMLOGFONTEX* lpelf,NEWTEXTMETRICEX* lpntm,DWORD nFontType,long lParam)
{
if(_tcscmp(temp,lpelf->elfLogFont.lfFaceName))
{
_tcscpy(temp,lpelf->elfLogFont.lfFaceName);
//mexPrintf("%d:%s---%d\n",strnum,temp,_tcsclen(temp));
pchar[strnum]=mxMalloc(_tcsclen(temp)*sizeof(_TCHAR)+1);//extra 1byte to contain '\0';
if(pchar[strnum]==NULL)
{
mexPrintf("Can't malloc the memory!\n");
return 0;
}
_tcscpy(pchar[strnum],temp);
strnum++;
}
}
void EnumFont()
{
LOGFONT lf;
HDC dc;
lf.lfCharSet=DEFAULT_CHARSET;
lf.lfFaceName[0]='\0';
lf.lfPitchAndFamily=0;
dc=GetWindowDC(NULL);
EnumFontFamiliesEx(dc,&lf,(FONTENUMPROC) MyEnumFontProc,0,0);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int i;
strnum=0;
EnumFont();
plhs[0]=mxCreateCharMatrixFromStrings(strnum,pchar);
for(i=0;i<strnum;i++)
mxFree(pchar[i]);
} -
2005-12-18
用matlab实现屏幕的抓取(抓屏)screensnap - [Matlab]
// matlab mex file to snap the screen
// compile to use>> mex screensnap.c user32.lib gdi32.lib
// usage:1, >>a=screensnap(0) %exclude the matlab window
// >>imshow(a);
// 2, >>a=screensnap(1); %include the matlab window
// >> imshow(a);
// designed by darnshong chenzushang@sina.com http://darnshong.52blog.net
// 2005,12,18
#include <windows.h>
#include <string.h>
#include "mex.h"void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int cx,cy,recnum;
int dims[3],i,j,k;
char *pchar,*mloc;
bool bshowmatlab;
HWND hwin,hactw;
HDC dc,memdc;
RECT rect;
HBITMAP hbitm,hold;
BITMAPINFOHEADER binfoh;
if(nrhs!=1)
mexErrMsgTxt("Need 1 argument!\n");
if(!mxIsDouble(prhs[0]))
mexErrMsgTxt("The input argument must be a numeric!\n");
if(*(double*)(mxGetData(prhs[0]))==0)
bshowmatlab=false;
else
bshowmatlab=true;
hactw=GetForegroundWindow();
hwin=GetDesktopWindow();
dc=GetWindowDC(hwin);
GetWindowRect(hwin,&rect);
cx=rect.right-rect.left;
cy=rect.bottom-rect.top;
mexPrintf("cx: %d cy: %d\n!",cx,cy);
memdc=CreateCompatibleDC(dc);
mexPrintf("Handles: %d %d %d\n!",hwin,dc,memdc);
hbitm=CreateCompatibleBitmap(dc,cx,cy);
if(hbitm==0)
mexErrMsgTxt("Fail to create a compatible bitmap!\n");
if (!(hold=SelectObject(memdc, hbitm)))
mexErrMsgTxt("Compatible Bitmap Selection!\n");
// Hide the application window.
if(!bshowmatlab)
{
ShowWindow(hactw, SW_HIDE);
Sleep(100);
}
//Copy color data for the entire display into a
//bitmap that is selected into a compatible DC.
if (!BitBlt(memdc,0,0,cx,cy,dc,0,0,SRCCOPY))
mexErrMsgTxt("Screen to Compat Blt Failed");
dims[0]=cy;
dims[1]=cx;
dims[2]=3;
plhs[0]=mxCreateNumericArray(3,dims,mxUINT8_CLASS,mxREAL);
pchar=(char*)mxGetData(plhs[0]);
binfoh.biSize=sizeof(BITMAPINFOHEADER);
binfoh.biWidth=cx;
binfoh.biHeight=-cy;
binfoh.biPlanes=1;
binfoh.biBitCount=24;
binfoh.biCompression=BI_RGB;
binfoh.biSizeImage=0;
binfoh.biXPelsPerMeter=0;
binfoh.biYPelsPerMeter =0;
binfoh.biClrUsed=0;
binfoh.biClrImportant=0;
mloc=(char*)mxMalloc(cx*cy*3);
recnum=GetDIBits(memdc,hbitm,0,cy,mloc,(BITMAPINFO*)&binfoh,DIB_RGB_COLORS);
mexPrintf("Copyed %d lines %d\n!",recnum,hbitm);
for(k=0;k<3;k++)
for(j=0;j<cy;j++)
for(i=0;i<cx;i++)
{
pchar[i*cy+j+k*cx*cy]=mloc[(j*cx+i)*3+2-k];
}
mxFree(mloc);
SelectObject(hbitm,hold);
DeleteDC(memdc);
ReleaseDC(hwin,dc);
DeleteObject(hbitm);
if(!bshowmatlab)
ShowWindow(hactw, SW_SHOW);
} -
function miffile(filename,var,width,depth)
% function miffile(filename,var,width,depth)
% It creates a 'mif' file called filename,which be written with var.
% The 'mif' file is a kind of file formats which is uesed in Altera's
% EDA tool,like maxplus II ,quartus II,to initialize the memory
% models,just like cam,rom,ram.
% Using this function,you can easily produce the 'mif' file written
% with all kinds of your data.
% If the size of 'var' is shorter than 'depth',0 will be written for the
% lefts.If the size of 'var' is greater than 'depth',than only 'depth' former
% data of 'var' will be written;
% the radix of address and data is hex
% filename --the name of the file to be created,eg,"a.mif",string;
% var ----the data to be writed to the file, can be 3D or less ,int or other fittable;
% width --the word size of the data,width>=1,int;
% depth --the number of the data to be writed,int;
%
% because matlab read the matrix is colum first,if you want to write
% the 'var' data in row first mode, just set var to var';
%
% example:
% a=uint8(rand(16,16)*256);
% miffile('randnum.mif',a,8,256);
if(nargin~=4) %% be tired to do more inupts check!
error('Need 4 parameters! Use help miffile for help!');
end,
fh=fopen(filename,'w+');
fprintf(fh,'--Created by darnshong.\r\n');
fprintf(fh,'--chenzushang@sina.com.\r\n');
fprintf(fh,'--%s.\r\n',datestr(now));
fprintf(fh,'WIDTH=%d;\r\n',width);
fprintf(fh,'DEPTH=%d;\r\n',depth);
fprintf(fh,'ADDRESS_RADIX=HEX;\r\n');
fprintf(fh,'DATA_RADIX=HEX;\r\n');
fprintf(fh,'CONTENT BEGIN\r\n');
%%%%%%
%%%%%%
var=rem(var,2^width);%% clip to fit the width;
[sx,sy,sz]=size(var);%% can only fit 3D or less;value=var(1,1,1);
sametotal=1;
idepth=0;
addrlen=1;
temp=16;
while(temp<depth) %%decide the length of addr
temp=temp*16;
addrlen=addrlen+1;
end,datalen=1;
while(temp<width) %%decide the length of data
temp=temp*16;
datalen=datalen+1;
end,for k=1:sz,
for j=1:sy,
for i=1:sx,
if(~((i==1 ) &&( j==1) &&( k==1)))
if(idepth<depth),
idepth=idepth+1;
if(value==var(i,j,k))
sametotal=sametotal+1;
continue;
else
if(sametotal==1)
fprintf(fh,['\t%' num2str(addrlen) 'X:%' num2str(datalen) 'X;\r\n'],idepth-1,value);
else
fprintf(fh,['\t[%' num2str(addrlen) 'X..%' num2str(addrlen) 'X]:%' num2str(datalen) 'X;\r\n'],idepth-sametotal,idepth-1,value);
end,
sametotal=1;
value=var(i,j,k);
end,
else
break;
end,
end,
end,
end,
end,if(idepth<depth)
if(sametotal==1)
fprintf(fh,['\t%' num2str(addrlen) 'X:%' num2str(datalen) 'X;\r\n'],idepth,value);
else
fprintf(fh,['\t[%' num2str(addrlen) 'X..%' num2str(addrlen) 'X]:%' num2str(datalen) 'X;\r\n'],idepth-sametotal+1,idepth,value);
end,
end,
if(idepth<depth-1)
if(idepth==(depth-2))
fprintf(fh,['\t%' num2str(addrlen) 'X:%' num2str(datalen) 'X;\r\n'],idepth+1,0);
else
fprintf(fh,['\t[%' num2str(addrlen) 'X..%' num2str(addrlen) 'X]:%' num2str(datalen) 'X;\r\n'],idepth+1,depth-1,0);
end,
end,
%%%%%%%%%%
%%%%%%%%%%
fprintf(fh,'END;\r\n');
fclose(fh); -
2005-05-31
从avi文件中提取图片(avi2bmp,avi2jpg,avi2gif,avi2png等) - [Matlab]
function avi2pic(avifile,pickind)
%function avi2pic(avifile,pickind)
% avifile-- the avi filename,like 'darnshong.avi','ioe.avi',etc;
% pickind-- the kind of image format,like 'jpg','bmp',etc
% supported export image
% format:'jpg','jpeg','bmp','tiff','tif','gif','png',etc
mov=aviread(avifile);
temp=size(mov);
fnum=temp(2);
for i=1:fnum,
strtemp=strcat(int2str(i),'.',pickind);
imwrite(mov(i).cdata(:,:,:),mov(i).colormap,strtemp);
end, -
seq格式文件是北京嘉恒中自图像技术有限公司生产的OK系列图像采集卡采集图像时保存的一种格式。文件头为20个字节的SEQINFO结构,紧跟其后按行顺序存放各帧原始图象数据。
序列文件信息结构:
typedef struct { //file info for seq
short iType; //文件类型(SQ、JP)
short iWidth; //宽度
short iHeight;// 高度
short iBitCount;//象元位数
short iFormType; //图象格式
short lBlockStep;//图象块跨距的低字
short iHiStep; //图象块跨距的高字
short lTotal; //图象总帧数的低字
short iHiTotal; //图象总帧数的高字
short iInterval;// 图象帧间隔数
} SEQINFO;
由于该格式是自定义的,普通的播放器并不支持,所以如果想在普通的播放器上播放,必须转化为一种标准的电影格式。以下是用matlab实现的将8位灰度的seq文件转化为avi格式电影的代码:
function readseq(seqf,avif)
%read the .seq file and play
fhl=fopen(seqf,'r');
a1=fread(fhl,1,'uint16');
a1=fread(fhl,2,'uint16');
fh=a1(1);fw=a1(2);
a1=fread(fhl,4,'uint16');
totalframe=fread(fhl,1,'uint32');
a1=fread(fhl,1,'uint16');
aviobj=avifile(avif);
aviobj.Quality = 100;
aviobj.compression='None';
cola=0:1/255:1;
cola=[cola;cola;cola];
cola=cola';
aviobj.colormap=cola;for i=1:totalframe
if(rem(i,15)==0) disp(i);
end
adata=uint8(fread(fhl,[fh,fw],'uint8'));
aviobj=addframe(aviobj,uint8(adata'));
end;
aviobj=close(aviobj);
fclose(fhl);仅供参考!
-
2005-04-09
将图像转化成avi格式电影(bmp2avi,jpg2avi,tiff2avi等) - [Matlab]
导师那有好些系列图像,想弄成电影。查了一下matlab的帮助,轻松地实现了,转化成avi格式电影!以下是代码:
function produceavifrompic(pfrom,pto,pext,navi)
aviobj = avifile(navi);
aviobj.Quality = 100;
aviobj.compression='None';
cola=0:1/255:1;
cola=[cola;cola;cola];%%黑白图像
cola=cola';
aviobj.colormap=cola;
for i=pfrom:pto
fname=strcat(num2str(i),pext)
adata=imread(fname);
aviobj = addframe(aviobj,uint8(adata));
end
aviobj=close(aviobj);以上是将一系列8位黑白图像转化成avi格式电影,如果是彩色图像,则如下
function produceavifrompic(pfrom,pto,pext,navi)
aviobj = avifile(navi);
aviobj.Quality = 100;
aviobj.compression='None';
for i=pfrom:pto
fname=strcat(num2str(i),pext)
adata=imread(fname);
aviobj = addframe(aviobj,uint8(adata));
end
aviobj=close(aviobj);挺简单的吧!快去试试!
-
2004-12-17
发现matlab不支持16位bmp图像的几种特殊格式(R5G6B5和X4R4G4B4) - [Matlab]
今天用photoshop做了几幅不同格式的16位bmp图像,包括X1R5G5B5格式、R5G6B5格式和X4R4G4B4格式。然后我用matlab的imread函数来读取,只有X1R5G5B5可以正确读取,其他两种格式无法读取,一读取就出错。我的matlab是7.01版本的,看来还是不支持R5G6B5和X4R4G4B4这两种格式的16位bmp图像 ! -
2004-12-14
用matlab读取16位、14位、12位灰度bmp图像(*.bmp) - [Matlab]
16位、14位、12位灰度bmp图像(*.bmp)并不是标准的格式,bmp图像只有16位的彩色图像而没有16位的灰度图像之说。所以,对于16位、14位、12位灰度bmp图像,一般是当做16位的彩色图像写入的,由于这个原因,计算机上看到的这些16位、14位、12位灰度bmp图像看起来都是彩色的,虽然我们写数据的时候写的是灰度的信息。用matlab可以读取16位的bmp图像,但是得到的数据是matlab解析过的彩色数据信息,RGB三个分量都是uint8,且matlab已经把RGB三分量的范围映射到0~255。这些并不是我们想要的bmp图像里的16位数据信息,必须经过适当的处理之后才能得到。只要得到了bmp图像里的16位数据信息,也就得到了那些非标准格式的灰度bmp图像(16位、14位、12位灰度bmp图像)的灰度信息。
倘若想保存16位、14位、12位灰度图像而又不让计算机解析成彩色图像,可以保存为*.png、*.tiff格式,这两种格式都支持16位的灰度图像。
另外还要提一下的是,由于我们现在所使用的计算机一般最高级也就24位的真彩色(RGB各8位),而要显示灰度图像,RGB三分量必须都相等,也就是说,用来显示灰度的其实只有8位,对于8位以上(不含8位)的灰度图像,计算机是没法正确显示的,无怪乎你若是把原来16位的灰度图像从bmp格式转化成png格式,图像反而不清楚了,因为16位灰度bmp格式时,计算机显示的是彩色图像,而16灰度png格式时,计算机显示的是灰色图像。
16位的bmp图像格式有两种,一种是R5G5B5,最高位不用,另一种是R5G6B5。
以下是matlab实现上述过程的源代码:
function b=read16graybmp(filename)
%usage: read16graybmp(filename)
%designed by darnshong ioe,cas
if(nargin~=1)
error('Need 1 parameters!');
end;
i=0:2^5-1;index5=floor(i*255.99/(2^5-1));%for 5bits
%index5=[0 8 16 24 33 41 49 57 66 74 82 90 99 107 115 123 132 140 148 156 165 173 181 189 198 206 214 222 231 239 247 255];
value5(index5 1)=0:2^5-1;
j=0:2^6-1;index6=floor(j*255.99/(2^6-1));%for 6bits
value6(index6 1)=0:2^6-1;
minfo=imfinfo(filename);
%if(strcmp(minfo.CompressionType,'none'))%for 555 format R5G5B5
a=double(imread(filename));% modified by darnshong,2006-09-06
b1=value5(a(:,:,1) 1);
b2=value5(a(:,:,2) 1);
b3=value5(a(:,:,3) 1);
b=bitshift(uint16(b1),10) bitshift(uint16(b2),5) uint16(b3);
% else % for 565 format R5G6B5 ,matlab not supported!
%a=imread(filename);
%b1=value5(a(:,:,1) 1);
%b2=value6(a(:,:,2) 1);
% b3=value5(a(:,:,3) 1);
% b=bitshift(uint16(b3),11) bitshift(uint16(b2),5) uint16(b1);
%end; -
2004-11-25
利用matlab从VHDL文件中提取端口信息 - [Matlab]
VHDL文件是文本文件,从VHDL文件中提取端口信息即是对字符串的解析。由于各种情况的存在,写出一个能百分之百正确提取端端口信息的程序并不容易。以下是我写的提取端口信息的m文件,用一些VHDL文件进行测试是能正确提取端口信息的。
该程序分为两个函数:getvhdlentity()和analyzeport()两个函数,其中,getvhdlentity()函数负责从VHDL文件中提取entity,而analyzeport()函数从是从entity中解析出端口信息。
function outset=getvhdlentity(vhdlfile)
outset={};
if (nargin~=1)
error('error use! Usage: outset=getvhdlport(vhdlfile)');
return;
end;
if ~(exist(vhdlfile,'file')==2)
error('the vhdlfile doesn''t exist!');
end;h=fopen(vhdlfile,'r');
tline=0;
tfentity=0;
entityname='';
while ~feof(h)
tline=fgetl(h);
copytline=tline;
tf=strfind(copytline,'--');
if(~isempty(tf))
copytline=copytline(1:tf(1)-1);
end;
tf=strfind(lower(copytline),'entity');
if(~isempty(tf))
tfentity=1;
copytline=tline(tf:numel(copytline));
[token,remstr]=strtok(copytline);
[token,remstr]=strtok(remstr);
entityname=token;
break;
end;
end;if tfentity==1
outset(end+1)=cellstr(tline);
while ~feof(h)
tline=fgetl(h);
tf=strfind(tline,'--');
if(~isempty(tf))
tline=tline(1:tf(1)-1);
end;
tf=strfind(lower(tline),'end ');
if(~isempty(tf))
tempend=tline(tf(1):numel(tline));
[token,tempend]=strtok(tempend);
[token,tempend]=strtok(tempend);
token=strtok(token,';');
if(strcmp(lower(token),'entity') ||strcmp(token,entityname))
outset(end+1)=cellstr(tline);
break;
end;
end;
tline=strtrim(tline);
if(~isempty(tline))
outset(end+1)=cellstr(tline);
end;
end;
end;
fclose(h);
outset=outset';
function outset=analyzeport(vhdlentity)
if(nargin~=1)
error('error use!\n Usage:outset=analyzeport(vhdlentity)');
end;
totalline=size(vhdlentity,1);
i=1;
outset={};
firstport=1;while(i<=totalline)
templ=vhdlentity{i};
findddot=find(templ==':');
if(~isempty(findddot))
templ(findddot(1))=' ';
b=size(findddot,2);
if(b==2)
templ=templ(1:findddot(2)-1);
end;
if(firstport==1)
findp=strfind(lower(templ),'port');
if(~isempty(findp))
[token,templ]=strtok(templ,'(');
templ=templ(2:numel(templ));
end;
end;
firstport=0;
[token,templ]=strtok(templ);
ass.name=token;
[token,templ]=strtok(templ);
ass.iotype=token;
[token,templ]=strtok(templ,';');
ass.datatype=strtrim(token);
dotnum=find(ass.name==',');
if(~isempty(dotnum))
strtemp=ass.name;
for i=1:numel(dotnum),
[token,strtemp]=strtok(strtemp,',');
ass.name=token;
outset{end+1}=ass;
end;
ass.name=strtok(strtemp,',');
end;
outset{end+1}=ass;
end;
i=i+1;
end;
slong=size(outset,2);
temp=outset{slong}.datatype;
numbracket1=numel(find(temp=='('));
numbracket2=numel(find(temp==')'));
if(numbracket1<numbracket2)
outset{slong}.datatype=temp(1:numel(temp)-1);
end; -
2004-11-20
普通文件与图像文件的相互转化(file2img和img2file) - [Matlab]
时下,好些论坛都提供贴图服务,也就是说,你可以把你喜欢的图像上传,与他人共享。但是如果是其他非图像和文本的文件的共享就不是很好办了。为此,我用matlab写了几个函数,用于把普通的文件(一切文件格式)转化成某些特定格式的图像文件(*.bmp,*.png,*.ras,*.tif,*.tiff)。通过这些转化而来的图像文件,你就可以与他人共享你的一切文件。对方只要保存了这个转化而来的图像文件,就可用我所写的函数完整地恢复原来的文件的面目,从而达到通过图像文件来共享一切文件的目的。
以下是我写的几个函数(file2imgdata、file2img、imgdata2file、img2file):
function dat=file2imgdata(filename,imgwidth)
%%dat=file2imgdata(filename,imgwidth)
%convert the common file to image data
%%--------------------the image map-------------------
% |-----------------the image width-------------------|
% |'csz'(3)+extension(20)+patch with '0'+file size(?)-|
% |the uint8 format data,acquired from the source file|
% |...................................................|
% |....................no data,patch with uint8(0)----|
% designed by darnshong,ioe,cas
if(~exist(filename,'file'))
error('The file does not exist!');
end;
[fpath,fname,fileext]=fileparts(filename);% get the file'extension
fileext=fileext(2:numel(fileext));
extnum=uint8(fileext);
if(numel(extnum)<20)
temp=zeros(1,20);
temp(1:numel(extnum))=extnum;
temp((numel(extnum)+1):20)=uint8('.');
extnum=temp;
else
error('the length of the file extension is large than 20');
end;
%%%%%%% get the source file sizes=dir(filename);
fsize=s.bytes;%get the file size.
fsize=num2str(uint32(fsize),'%d');
fsize=uint8(fsize);
extralen=imgwidth-3-20;
if(numel(fsize)<=extralen)
temp=zeros(1,extralen);
temp(1:extralen-numel(fsize))=uint8('0');
temp((extralen+1-numel(fsize)):extralen)=fsize;
fsize=temp;
else
error('the length of the file size is too large!');
end;
dat=[];
dat(1,:)=[uint8('czs'),extnum,fsize];
fsrc=fopen(filename,'r');
totalline=uint32(ceil(s.bytes/imgwidth));
for i=1:totalline-1
dat(end+1,:)=fread(fsrc,imgwidth);
end;
temp=fread(fsrc,imgwidth); %not enough data,so patch with 0;
temp1=zeros(1,imgwidth);
temp1(1:numel(temp))=temp;
dat(end+1,:)=temp1;
fclose(fsrc);
dat=uint8(dat);%%%%%%%%%%%%%%%%%%%%%%%%%%%
function yy=file2img(commonfile,imgfile,imgwidth)
%yy=file2img(commonfile,imgfile,imgwidth)
%convert the common file like .exe,.doc,to the image file.
%thus you can post your common file as a image file.
% designed by darnshong,ioe,cas
if(nargin~=3)
error('Input parameters error!Require 3 parameters!');
end;
yy=file2imgdata(commonfile,imgwidth);
finddot=find(imgfile=='.');
imgext=imgfile(finddot(1)+1:end);
if~(strcmp(imgext,'bmp') || strcmp(imgext,'png') || strcmp(imgext,'ras') ||...
strcmp(imgext,'tif') || strcmp(imgext,'tiff'))
error('Not support image format!The image file format should be *.bmp,*.png,*.ras,*.tif,*.tiff');
end;
imwrite(yy,imgfile);
%%%%%%%%%%%%%%%%%%%%%%%%%%function imgdata2file(dat,filenoext)
%%%% imgdata2file(dat,filenoext)
% ----dat,the image data
% convert the imagedata to the common file
%%dat=file2imgdata(filename,imgwidth)
%%--------------------the image map-------------------
% |-----------------the image width-------------------|
% |'csz'(3)+extension(20)+patch with '0'+file size(?)-|
% |the uint8 format data,acquired from the source file|
% |...................................................|
% |....................no data,patch with uint8(0)----|
% designed by darnshong,ioe,castestczs=dat(1,1:3);%test if the image data is valid.
testczs=char(testczs);
if(~strcmp(testczs,'czs'))
error('wrong image data!');
end
imgwidth=size(dat,2);
finddot=find(dat(1,:)==uint8('.'));
ext=dat(1,4:finddot(1)-1);%get the common file's extension
ext=char(ext);
fsize=dat(1,(finddot(end)+1):imgwidth);%get the common file's sizefsize=str2double(char(fsize));
dstfile=strcat(filenoext,'.',ext);
fdst=fopen(dstfile,'w');
totalline=uint32(ceil(fsize/imgwidth));
for i=2:totalline,
fwrite(fdst,dat(i,:),'uint8');
end;
lastline=dat(totalline+1,1:(fsize-imgwidth*(totalline-1)));
fwrite(fdst,lastline,'uint8');
fclose(fdst);%%%%%%%%%%%%%%%%%%%%%%%%%%
function yy=img2file(imgfile,commonfilenoext)
%%% yy=img2file(imgfile,commonfilenoext)
% convert the image file to the common file
% thus you can restore the common file from the image file.
% designed by darnshong,ioe,cas
if(nargin~=2)
error('Input parameters error!Require 2 parameter!');
end;
finddot=find(imgfile=='.');
imgext=imgfile(finddot(1)+1:end);
if~(strcmp(imgext,'bmp') || strcmp(imgext,'png') || strcmp(imgext,'ras') ||...
strcmp(imgext,'tif') || strcmp(imgext,'tiff'))%only support some image format
error('Not support image format!The image file format should be *.bmp,*.png,*.ras,*.tif,*.tiff');
end; %%%% because the *.jpg image format is lossy compression,it can't be used.
yy=imread(imgfile);
imgdata2file(yy,commonfilenoext);
%%%%%%%%%%%%%%%%%%%%%%%%%%%% -
2004-11-08
应用图像数据仿真VHDL文件(基于Matlab与Modelsim)(三) - [Matlab]
(4) GUI界面及运行后结果:
GUI m文件的全部程序如下:
function varargout = view_ctl(varargin)
% VIEW_CTL M-file for view_ctl.fig
% VIEW_CTL, by itself, creates a new VIEW_CTL or raises the existing
% singleton*.
%
% H = VIEW_CTL returns the handle to a new VIEW_CTL or the handle to
% the existing singleton*.
%
% VIEW_CTL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in VIEW_CTL.M with the given input arguments.
%
% VIEW_CTL('Property','Value',...) creates a new VIEW_CTL or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before view_ctl_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to view_ctl_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help view_ctl
% Last Modified by GUIDE v2.5 02-Nov-2004 11:03:21
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @view_ctl_OpeningFcn, ...
'gui_OutputFcn', @view_ctl_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before view_ctl is made visible.
function view_ctl_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to view_ctl (see VARARGIN)
% Choose default command line output for view_ctl
handles.output = hObject;
handles.vhdlfileext='';
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes view_ctl wait for user response (see UIRESUME)
% uiwait(handles.viewctl_fig);
set(handles.viewM_button,'Enable','off');
% --- Outputs from this function are returned to the command line.
function varargout = view_ctl_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function imgfile_edit_Callback(hObject, eventdata, handles)
% hObject handle to imgfile_edit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of imgfile_edit as text
% str2double(get(hObject,'String')) returns contents of imgfile_edit as a double
% --- Executes during object creation, after setting all properties.
function imgfile_edit_CreateFcn(hObject, eventdata, handles)
% hObject handle to imgfile_edit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in browsefile_button.
function browsefile_button_Callback(hObject, eventdata, handles)
% hObject handle to browsefile_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename,pathname]=uigetfile({'*.jpg';'*.bmp';'*.gif'});
if(~isempty(filename))
set(handles.imgfile_edit,'String',[pathname filename]);
guidata(hObject,handles);
end;
% --- Executes on button press in share_cb.
function share_cb_Callback(hObject, eventdata, handles)
% hObject handle to share_cb (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of share_cb
h=[handles.Portnum_text handles.Portnum_edit handles.Portnum_add];
if get(hObject,'value')
set(h,'Enable','off');
else
set(h,'Enable','on');
end;
function Portnum_edit_Callback(hObject, eventdata, handles)
% hObject handle to Portnum_edit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of Portnum_edit as text
% str2double(get(hObject,'String')) returns contents of Portnum_edit as a double
port=str2double(get(hObject,'String'));
if ~isnan(port),
port=round(port);
if port<0 || port>66535,
msg = {['Specified TCP/IP port number: ''' num2str(port) ''' is illegal.'],...
'Please select an unused value from 1024 to 49151,',...
'or select 0 to let the computer choose the port number.' };
errordlg(msg,'Port Selection Error','modal')
port=get(hObject,'UserData');
set(hObject,'String',num2str(port));
else
if port~=0 && (port<1024 || port>49151),
msg = {['Specified TCP/IP port number: ''' num2str(port) ''' is not recommended.'],...
'Please select an unused value from 1024 to 49151,',...
'or select 0 to let the computer choose the port number.' };
warndlg(msg,'Port Selection Warning','modal')
end;
set(hObject,'UserData',port);
set(hObject,'String',num2str(port));
end;
else
msg={['Please input digital port num' ]};
errordlg(msg,'port num input error','modal');
end;
% --- Executes during object creation, after setting all properties.
function Portnum_edit_CreateFcn(hObject, eventdata, handles)
% hObject handle to Portnum_edit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end;
% --- Executes on button press in start_button.
function start_button_Callback(hObject, eventdata, handles)
% hObject handle to start_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global imgfile;
global figfile;
warning off;
disp('To enable access from ModelSim, HDLDaemon is used with appropriate link settings.');
disp('The following messages are produced by HDLDaemon to indicate link status ...');
vhdlfilenoext=strrep(handles.vhdlfileext,'.vhd','');
imgfile=get(handles.imgfile_edit,'String');
figfile=[mfilename,'.fig'];
%disp('imgfile:');disp(imgfile);
%disp('figfile:');disp(figfile);
if(isempty(imgfile))
return;
end;
if get(handles.share_cb,'value')
dstatus=hdldaemon('status');
if isempty(dstatus)
dstatus=hdldaemon;
elseif strcmp(dstatus.comm,'shared memory')
if strcmp(computer,'GLNX86')
hdldaemon('kill');
dstatus=hdldaemon;
end;
elseif strcmp(dstatus.comm,'sockets')
disp('Shutting down HDLDaemon to restart it with shared memory');
hdldaemon('kill');
dstatus=hdldaemon;
else
error('unexpected return value from hdldaemon(''status'')');
end;
vsim_comm='';
else
dstatus=hdldaemon('status');
portnum=get(handles.Portnum_edit,'UserData');
%%portnum=round(str2double((get(handles.Portnum_edit,'String'));