话不多说,直接上源码:

int GetMidValue(Mat& input)
{
	int rows = input.rows;
	int cols = input.cols;
	float histogram[256] = { 0 };
    //先计算图像的直方图
	for (int i = 0; i < rows; ++i)
	{
		///获取i行首像素的指针
		const uchar *p = input.ptr<uchar>(i);
		///遍历i行像素
		for (int j = 0; j < cols; ++j)
		{
			//cout << int(*p++) << endl;
			histogram[int(*p++)]++;
		}
	}
	int HalfNum = rows * cols / 2;
	int tempSum = 0;
	for (int i = 0; i < 255; i++)
	{
		tempSum = tempSum + histogram[i];
		if (tempSum > HalfNum)
		{
			return i;
		}
	}
	return 0;
}

输入为Mat类图像,返回为图像像素值中位数,返回为0则计算有误。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐