hough直线变换

// 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++;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值