// houghLine.cpp : 定义控制台应用程序的入口点。
//
#include <stdlib.h>
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
void houghChange(char *image, int w, int h, float *houghMatrix, int the, int rho);
void main()
{
IplImage *src = cvLoadImage("1.bmp",CV_LOAD_IMAGE_GRAYSCALE);
IplImage *byte = cvCreateImage(cvGetSize(src), 8, 1);
//cvThreshold(src, byte, 127, 255, CV_THRESH_BINARY);
cvAdaptiveThreshold(src, byte, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY, 3, 7);
//cvNamedWindow("src", 1);
cvNamedWindow("byte",1);
//cvShowImage("src", src);
cvShowImage("byte", byte);
cvWaitKey(30);
int the = 180;
int w = src->width;
int h = src->height;
int rho = (int)(sqrt(w*w*1.0f+h*h));
float *houghMatrix = (float *)calloc(the*rho*2, sizeof(float));
houghChange(byte->imageData, w, h, houghMatrix, the, rho);
int num = 0;
int prerho = -1;
int prethe = -1;
for(int j = 0; j < the; j++)
{
if(prerho < 0 && j - prethe > 10)//认为计算的平行线角度的最大差值
{
prerho = -1;
prethe = -1;
}
for(int i = 0; i < rho*2; i++)//-rho
{
if(houghMatrix[i*the+j] > 100)//构成直线的最少点数
{
if(prerho < 0)
{
num++;
prerho = i;
prethe = j;
}
else
{
if(abs(i-prerho) > 10)//合并直线
//if(abs(sqrt(i*i*1.0f+j*j)-sqrt(prerho*prerho*1.0f+prethe*prethe)) > 10)
{
num++;
prerho = i;
prethe = j;
}
else
{
}
}
}
}
}
printf("linenum = %d\n", num);
system("pause");
}
//hough变化,得到变化的极坐标矩阵
void houghChange(char *image, int w, int h, float *houghMatrix, int the, int rho)
{
float *SIN = (float *)calloc(the, sizeof(float));
float *COS = (float *)calloc(the, sizeof(float));
for(int i = 0; i < the; i++)
{
*(SIN+i) = sin(i*CV_PI/180.0f);
*(COS+i) = cos(i*CV_PI/180.0f);
}
char *Data = image;
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
if((uchar)(*Data) < 128)//黑点
{
int r = 0;
for(int k = 0; k < the; k++)//遍历所有角度
{
r = (int)(i*SIN[k]+j*COS[k]);
r = r + rho;
houghMatrix[r*the+k]++;;
}
}
Data++;
}
}
}
hough直线变换
最新推荐文章于 2024-01-05 13:57:04 发布