opencv直方图(上)

// 3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"opencv243.h"

using namespace std;
using namespace cv;


int _tmain(int argc, _TCHAR* argv[])
{  
	vector<int> hist(256);
	Mat img=imread("C:\\Users\\sony\\Desktop\\Lena.jpg",0);
	Mat histImg(256,256,img.type());  //表示256行,256列
	for(auto it=img.begin<uchar>();it!=img.end<uchar>();++it)
		hist[*it]++;
	for(int i=0;i!=hist.size();++i)
	{   Point p1(i,0);
	    Point p2(i,hist[i]/20);
		line(histImg,p1,p2,0);
	}
	for(int i=0;i!=hist.size();++i)
		cout<<"灰度值为"<<i<<"的像素点的个数为:"<<hist[i]<<endl;
	flip(histImg,histImg,0);            //0表示对x轴翻转
	imshow("histImg",histImg);
	waitKey(0);
	return 0;
}

这里的cv::Mat::begin()返回的是可读可写的迭代器,后面加了const表示可读迭代器

以下是用calcHist函数的方法画直方图,代码如下:

// 4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"opencv243.h"
#include"stdlib.h"

using namespace std;
using namespace cv;



Mat getImage(const Mat& hist, Size imgSize)
{
	Mat histImg(imgSize, CV_8UC3);
	int Padding = 10;   //一个基点偏差
	int W = imgSize.width - 2 * Padding;
	int H = imgSize.height - 2 * Padding;
	double _max;
	minMaxLoc(hist, NULL, &_max);
	double Per = (double)H / _max;
	const Point Orig(Padding, imgSize.height-Padding);
	int bin = W / (hist.rows + 2);

	//画方柱
	for (int i = 1; i <= hist.rows; i++)
	{
		Point pBottom(Orig.x + i * bin, Orig.y);
		Point pTop(pBottom.x, pBottom.y - Per * hist.at<float>(i-1));
		line(histImg, pBottom, pTop, Scalar(255, 0, 0), bin);
	}

	

	return histImg;
}

int _tmain(int argc, _TCHAR* argv[])
{

	Mat img=imread("C:\\Users\\sony\\Desktop\\Airplane.jpg",0);
	Mat hist;
	int histSize=256;
	float range[]={0,255};
	const float* histRange={range};

	bool uniform=true;
	bool accumulate=false;

	calcHist(&img,1,0,Mat(),hist,1,&histSize,&histRange,uniform,accumulate);
	

	Mat histImg=getImage(hist,Size(600,400));

	imshow("1",histImg);

	
	waitKey(0);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值