如题
PS:下面是哈夫直线检测的vc版本的代码,请高手帮我翻译成C#版本的
BOOL Hough(HWND hWnd)
{
//定义一个自己的直线结构
typedef struct{
int topx; //最高点的x坐标
int topy; //最高点的y坐标
int botx; //最低点的x坐标
int boty; //最低点的y坐标
}MYLINE;
DWORD OffBits,BufSize;
LPBITMAPINFOHEADER lpImgData;
LPSTR lpPtr;
HDC hDc;
LONG x,y;
long i,maxd;
int k;
int Dist,Alpha;
HGLOBAL hDistAlpha,hMyLine;
Int *lpDistAlpha;
MYLINE *lpMyLine,*TempLine,MaxdLine;
static LOGPEN rlp={PS_SOLID,1,1,RGB(255,0,0)};
HPEN rhp;
//我们处理的实际上是256级灰度图,不过只用到了0和255两种颜色。
if( NumColors!=256){
MessageBox(hWnd,"Must be a mono bitmap with grayscale palette!",
"Error Message",MB_OK|MB_ICONEXCLAMATION);
return FALSE;
}
//计算最大距离
Dist=(int)(sqrt((double)bi.biWidth*bi.biWidth+
(double)bi.biHeight*bi.biHeight)+0.5);
Alpha=180 /2 ; //0 到 to 178 度,步长为2度
//为距离角度数组分配内存
if((hDistAlpha=GlobalAlloc(GHND,(DWORD)Dist*Alpha*
sizeof(int)))==NULL){
MessageBox(hWnd,"Error alloc memory!","Error Message",
MB_OK|MB_ICONEXCLAMATION);
return FALSE;
}
//为记录直线端点的数组分配内存
if((hMyLine=GlobalAlloc(GHND,(DWORD)Dist*Alpha*
sizeof(MYLINE)))==NULL){
GlobalFree(hDistAlpha);
return FALSE;
}
OffBits=bf.bfOffBits-sizeof(BITMAPFILEHEADER);
//BufSize为缓冲区大小
BufSize=OffBits+bi.biHeight*LineBytes;
lpImgData=(LPBITMAPINFOHEADER)GlobalLock(hImgData);
lpDistAlpha=(int *)GlobalLock(hDistAlpha);
lpMyLine=(MYLINE *)GlobalLock(hMyLine);
for (i=0;i<(long)Dist*Alpha;i++){
TempLine=(MYLINE*)(lpMyLine+i);
(*TempLine).boty=32767; //初始化最低点的y坐标为一个很大的值
}
for (y=0;y<bi.biHeight;y++){
//lpPtr指向位图数据
lpPtr=(char *)lpImgData+(BufSize-LineBytes-y*LineBytes);
for (x=0;x<bi.biWidth;x++)
if(*(lpPtr++)==0) //是个黑点
for (k=0;k<180;k+=2){
//计算距离i
i=(long)fabs((x*cos(k*PI/180.0)+y*sin(k*PI/180.0)));
//相应的数组元素加1
*(lpDistAlpha+i*Alpha+k/2)=*(lpDistAlpha+i*Alpha+k/2)+1;
TempLine=(MYLINE*)(lpMyLine+i*Alpha+k/2);
if(y> (*TempLine).topy){
//记录该直线最高点的x,y坐标
(*TempLine).topx=x;
(*TempLine).topy=y;
}
if(y< (*TempLine).boty){
//记录该直线最低点的x,y坐标
(*TempLine).botx=x;
(*TempLine).boty=y;
}
}
}
maxd=0;
for (i=0;i<(long)Dist*Alpha;i++){
TempLine=(MYLINE*)(lpMyLine+i);
k=*(lpDistAlpha+i);
if(k > maxd){
//找到数组元素中最大的,及相应的直线端点
maxd=k;
MaxdLine.topx=(*TempLine).topx;
MaxdLine.topy=(*TempLine).topy;
MaxdLine.botx=(*TempLine).botx;
MaxdLine.boty=(*TempLine).boty;
}
}
hDc = GetDC(hWnd);
rhp = CreatePenIndirect(&rlp);
SelectObject(hDc,rhp);
MoveToEx(hDc,MaxdLine.botx,MaxdLine.boty,NULL);
//在两端点之间画一条红线用来标识
LineTo(hDc,MaxdLine.topx,MaxdLine.topy);
DeleteObject(rhp);
ReleaseDC(hWnd,hDc);
//释放内存及资源
GlobalUnlock(hImgData);
GlobalUnlock(hDistAlpha);
GlobalFree(hDistAlpha);
GlobalUnlock(hMyLine);
GlobalFree(hMyLine);
return TRUE;
}