jashliao 用 VC++ 实现 fanfuhan OpenCV 教学071 ~ opencv-071-彩色转二值化图像(直接使用Canny) 后 用图像形态学击中&击不中(morphologyEx)实现找出绳网中绳结位置


资料来源: https://fanfuhan.github.io/

https://fanfuhan.github.io/2019/04/22/opencv-071/


GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV

https://github.com/jash-git/jashliao-implements-FANFUHAN-OPENCV-with-VC

★前言:


★主题:
    形态学的击中&击不中操作,根据结构元素不同,可以提取二值图像中的一些特殊区域,得到我们想要的结果。


C++

// VC_FANFUHAN_OPENCV071.cpp : 定义主控台应用程式的进入点。
//
/*
// Debug | x32
通用属性
| C/C++
|	| 一般
|		| 其他 Include 目录 -> ..\..\opencv411_x64\include
|
| 连结器
| 	|一一般
|		|  其他程式库目录 -> ..\..\opencv411_x64\lib
|
| 	|一输入
|		| 其他相依性 -> opencv_world411d.lib;%(AdditionalDependencies)
// Releas | x64
组态属性
| C/C++
|	| 一般
|		| 其他 Include 目录 -> ..\..\opencv411_x64\include;%(AdditionalDependencies)
|
| 连结器
| 	|一般
|		| 其他程式库目录 -> ..\..\opencv411_x64\lib;%(AdditionalDependencies)
|
| 	|一输入
|		| 其他相依性 -> opencv_world411.lib;%(AdditionalDependencies)
*/

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

using namespace std;
using namespace cv;

void blur_demo(Mat &image, Mat &sum);
void edge_demo(Mat &image, Mat &sum);
int getblockSum(Mat &sum, int x1, int y1, int x2, int y2, int i);

void showHistogram(InputArray src, cv::String StrTitle);
void backProjection_demo(Mat &mat, Mat &model);
void blur3x3(Mat &src, Mat *det);

void add_salt_pepper_noise(Mat &image);
void add_gaussian_noise(Mat &image);

void USMImage(Mat src, Mat &usm, float fltPar);

void pyramid_up(Mat &image, vector &pyramid_images, int level);
void pyramid_down(vector &pyramid_images);

void laplaian_demo(vector &pyramid_images, Mat &image);

void connected_component_demo(Mat &image);
void componentwithstats_demo(Mat &image);

void contours_info(Mat &image, vector> &pts);
void contours_info(Mat &image, vector> &pts, int threshold01, int threshold02);

void  open_demo(bool blnopen);
void  close_demo();

void pause()
{
	printf("Press Enter key to continue...");
	fgetc(stdin);
}
int main()
{
	Mat src = imread("../../images/cross.png");//Mat src = imread("../../images/test.png");
	if (src.empty())
	{
		cout << "could not load image.." << endl;
		pause();
		return -1;
	}
	else
	{
		imshow("input_src", src);
		showHistogram(src, "Histogram_input_src");

		// 二值图像
		Mat gray, binary, result;
		cvtColor(src, gray, COLOR_BGR2GRAY);
		threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
		imshow("input_binary", binary);

		// 击中击不中
		Mat se = getStructuringElement(MORPH_CROSS, Size(11, 11));
		morphologyEx(binary, result, MORPH_HITMISS, se);
		imshow("bit_and_miss", result);

		// 轮廓绘制
		vector> contours;
		vector hierarchy;
		findContours(result, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
		for (size_t c = 0; c < contours.size(); c++) {
			Rect rect = boundingRect(contours[c]);
			/*
			double area = contourArea(contours[c]);
			if (area < 200) {
				continue;
			}
			int h = rect.height;
			int w = rect.width;
			if (h >(3 * w) || h < 20) {
				continue;
			}
			*/

			rectangle(src, rect, Scalar(0, 0, 255));
		}
		imshow("result", src);

		waitKey(0);
	}
	return 0;
}
void close_demo()
{
	//读取图像     
	Mat src = imread("../images/morph3.png");
	imshow("close_demo_input", src);

	//二值图像
	Mat gray, binary;
	cvtColor(src, gray, COLOR_BGR2GRAY);
	threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("close_demo_binary", binary);

	//闭操作//
	//Mat se = getStructuringElement(MORPH_ELLIPSE, Size(30, 30), Point(-1, -1));
	//Mat se = getStructuringElement(MORPH_RECT, Size(30, 30), Point(-1 , -1));
	Mat se = getStructuringElement(MORPH_RECT, Size(35, 35), Point(-1, -1));
	morphologyEx(binary, binary, MORPH_CLOSE, se);
	imshow("close_demo rect=35,35 ", binary);
}

void open_demo(bool blnopen)
{
	//读取图像     
	Mat src = imread("../images/fill.png");
	imshow("open_demo_input", src);

	//二值图像
	Mat gray, binary;
	cvtColor(src, gray, COLOR_BGR2GRAY);
	if (blnopen)
	{
		threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
	}
	else
	{
		threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	}
	imshow("open_demo_binary", binary);

	//开操作 -去除黑色杂讯 强化/获取 连通元件(mask) 保留长(x=25)底线(y=1)
	Mat se = getStructuringElement(MORPH_RECT, Size(25, 1), Point(-1, -1));
	if (blnopen)
	{
		morphologyEx(binary, binary, MORPH_OPEN, se);
	}
	else
	{
		morphologyEx(binary, binary, MORPH_CLOSE, se);//
		threshold(binary, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
	}
	imshow("open_op", binary);

	//绘制填空位置
	vector < vector > contours;
	vector  hierarhy;
	findContours(binary, contours, hierarhy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(-1, -1));
	for (size_t t = 0; t < contours.size(); t++)
	{
		Rect roi = boundingRect(contours[t]);
		roi.y = roi.y - 10;
		roi.height = 12;
		rectangle(src, roi, Scalar(0, 0, 255));
	}

	//显示结果
	imshow("open_demo", src);
}
void contours_info(Mat &image, vector> &pts)//目标物为同类型(颜色) ~ 抓取轮廓(findContours)函数
{
	// 去噪声与二值化
	//彩色转二值化步骤(SOP) 彩色 -> 高斯模糊(去杂讯) -> 转灰阶 -> 二值化
	Mat dst, gray, binary00;
	GaussianBlur(image, dst, Size(3, 3), 0, 0);
	cvtColor(dst, gray, COLOR_BGR2GRAY);
	threshold(gray, binary00, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("binary00", binary00);

	vector hierarchy00;
	Scalar color = Scalar(255, 0, 0);
	/*
	void findContours(InputOutputArray image,OutputArrayOfArrays contours,OutputArray hierarchy,int mode,int method,Point offset = Point() )
	各个参数详解如下:
	image表示输入图像,必须是二值图像,二值图像可以threshold输出、Canny输出、inRange输出、自适应阈值输出等。
	contours获取的轮廓,每个轮廓是一系列的点集合
	hierarchy轮廓的层次信息,每个轮廓有四个相关信息,分别是同层下一个、前一个、第一个子节点、父节点
	mode 表示轮廓寻找时候的拓扑结搆返回
	-RETR_EXTERNAL表示只返回最外层轮廓
	-RETR_TREE表示返回轮廓树结搆
	method表示轮廓点集合取得是基于什么算法,常见的是基于CHAIN_APPROX_SIMPLE链式编码方法
	*/
	findContours(binary00, pts, hierarchy00, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());

}
void contours_info(Mat &image, vector> &pts, int threshold01, int threshold02)//目标物非同类型(颜色) ~ 抓取轮廓(findContours)函数
{
	Mat dst, gray, binary01;
	//彩色转二值化步骤(直接使用Canny)
	/*
	void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false )
	image, edges:输入和输出的图片。
	threshold1, threshold2:用来区分 strong edge 和 weak edge,范围都是 0 ~ 255,会在实作过程中进一步讨论,通常选择 threshold2 / threshold1 = 1/2 ~ 1/3,例如 (70, 140), (70, 210)
	apertureSize:用来计算梯度的 kernel size,也就是 Sobel 的 ksize
	L2gradient:选择要用 L1 norm(绝对值平均)还是 L2 norm(平方根)当作梯度的大小。预设是用 L1 norm
	*/
	Canny(image, binary01, threshold01, threshold02);

	// 膨胀
	/*
	OpenCV提供getStructuringElement()让我们得到要进行侵蚀或膨胀的模板
	Mat getStructuringElement(int shape, Size ksize, Point anchor=Point(-1,-1))
	shape:模板形状,有MORPH_RECT、MORPH_ELLIPSE、MORPH_CROSS三种可选。
	ksize:模板尺寸。
	*/
	Mat k = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
	/*
	OpenCV膨胀
	dilate(const Mat &src, Mat &dst, Mat kernel, Point anchor=Point(-1,-1), int iterations=1)
	src:输入图,可以多通道,深度可为CV_8U、CV_16U、CV_16S、CV_32F或CV_64F。
	dst:输出图,和输入图尺寸、型态相同。
	kernel:结构元素,如果kernel=Mat()则为预设的3×3矩形,越大膨胀效果越明显。
	anchor:原点位置,预设为结构元素的中央。
	iterations:执行次数,预设为1次,执行越多次膨胀效果越明显。
	*/
	dilate(binary01, binary01, k);
	imshow("binary01", binary01);

	vector hierarchy01;
	Scalar color = Scalar(255, 0, 0);
	findContours(binary01, pts, hierarchy01, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
}

void componentwithstats_demo(Mat &image)//八方炼码:元件标记/寻找/计算(计数)/参数:中心位置、起始座标、长、宽、面积,取得分类的所需资讯作业 + 绘制各元件的外矩形
{
	// extract labels
	//彩色转二值化步骤(SOP) 彩色 -> 高斯模糊(去杂讯) -> 转灰阶 -> 二值化
	Mat gray, binary;
	GaussianBlur(image, image, Size(3, 3), 0);
	cvtColor(image, gray, COLOR_BGR2GRAY);
	threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("input_binary", binary);
	showHistogram(binary, "Histogram_input_binary");

	Mat labels = Mat::zeros(image.size(), CV_32S);
	Mat stats, centroids;
	int num_labels = connectedComponentsWithStats(binary, labels, stats, centroids, 8, 4);
	cout << "total labels : " << num_labels - 1 << endl;
	vector colors(num_labels);

	// 背景颜色
	colors[0] = Vec3b(0, 0, 0);

	// 目标颜色
	RNG rng;
	for (int i = 1; i < num_labels; ++i) {
		colors[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
	}

	// 抽取统计信息
	Mat dst = image.clone();
	for (int i = 1; i < num_labels; ++i) {
		// 中心位置
		int cx = centroids.at(i, 0);
		int cy = centroids.at(i, 1);

		// 统计信息
		int x = stats.at(i, CC_STAT_LEFT);
		int y = stats.at(i, CC_STAT_TOP);
		int w = stats.at(i, CC_STAT_WIDTH);
		int h = stats.at(i, CC_STAT_HEIGHT);
		int area = stats.at(i, CC_STAT_AREA);

		// 中心位置绘制
		circle(dst, Point(cx, cy), 2, Scalar(0, 255, 0), 2);

		// 外接矩形
		Rect rect(x, y, w, h);
		rectangle(dst, rect, colors[i]);
		putText(dst, format("num:%d", i), Point(x, y), FONT_HERSHEY_SIMPLEX,
			.5, Scalar(0, 0, 255), 1);
		printf("num : %d, rice area : %d\n", i, area);
	}

	imshow("result", dst);
}

void connected_component_demo(Mat &image) //八方炼码 元件 计数(计算) 数量 / 标色
{
	// extract labels
	Mat gray, binary;

	//彩色转二值化步骤(SOP) 彩色 -> 高斯模糊(去杂讯) -> 转灰阶 -> 二值化
	GaussianBlur(image, image, Size(3, 3), 0);
	cvtColor(image, gray, COLOR_BGR2GRAY);
	threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("input_binary", binary);
	showHistogram(binary, "Histogram_input_binary");

	//计算(计数) 元件(mask) 数量 和 所需元素颜色数量阵列
	/*
	参数介绍如下:
	image:也就是输入图像,必须是二值图,即8位单通道图像。(因此输入图像必须先进行二值化处理才能被这个函数接受)
	返回值:
	num_labels:所有连通域的数目
	labels:图像上每一像素的标记,用数字1、2、3…表示(不同的数字表示不同的连通域)
	*/
	Mat labels = Mat::zeros(image.size(), CV_32S);//背景也会被算一个区域
	int num_labels = connectedComponents(binary, labels, 8, CV_32S);//数量
	cout << "total labels : " << num_labels - 1 << endl;
	vector colors(num_labels);

	// 背景颜色
	colors[0] = Vec3b(0, 0, 0);

	// 目标颜色
	RNG rng;
	for (int i = 1; i < num_labels; ++i) {
		colors[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
	}

	// 给结果着色
	Mat dst = Mat::zeros(image.size(), image.type());
	for (int row = 0; row < image.rows; ++row) {
		for (int col = 0; col < image.cols; ++col) {
			int label = labels.at(row, col);
			if (label == 0) continue;
			dst.at(row, col) = colors[label];
		}
	}

	imshow("result", dst);
}

void laplaian_demo(vector &pyramid_images, Mat &image)//拉普拉斯金字塔
{
	for (int i = pyramid_images.size() - 1; i > -1; --i)
	{
		Mat dst;
		if (i - 1 < 0)
		{
			pyrUp(pyramid_images[i], dst, image.size());
			subtract(image, dst, dst);//图像相减
			dst = dst + Scalar(127, 127, 127); //调亮度, 实际中不能这么用
			imshow(format("laplaian_layer_%d", i), dst);
		}
		else
		{
			pyrUp(pyramid_images[i], dst, pyramid_images[i - 1].size());
			subtract(pyramid_images[i - 1], dst, dst);//图像相减
			dst = dst + Scalar(127, 127, 127); //调亮度, 实际中不能这么用
			imshow(format("laplaian_layer_%d", i), dst);
		}
	}
}

void pyramid_down(vector &pyramid_images)//高斯金字塔01
{
	for (int i = pyramid_images.size() - 1; i > -1; --i) {
		Mat dst;
		/*
		pyrUp(tmp, dst, Size(tmp.cols * 2, tmp.rows * 2))
		tmp: 当前影象, 初始化为原影象 src 。
		dst : 目的影象(显示影象,为输入影象的两倍)
		Size(tmp.cols * 2, tmp.rows * 2) : 目的影象大小, 既然我们是向上取样, pyrUp 期待一个两倍于输入影象(tmp)的大小。
		*/
		pyrUp(pyramid_images[i], dst);
		imshow(format("pyramid_down_%d", i), dst);
	}
}

void pyramid_up(Mat &image, vector &pyramid_images, int level)//高斯金字塔02
{
	Mat temp = image.clone();
	Mat dst;
	for (int i = 0; i < level; ++i)
	{
		/*
		pyrDown( tmp, dst, Size( tmp.cols/2, tmp.rows/2 ))
		tmp: 当前影象, 初始化为原影象 src 。
		dst: 目的影象( 显示影象,为输入影象的一半)
		Size( tmp.cols/2, tmp.rows/2 ) :目的影象大小, 既然我们是向下取样, pyrDown 期待一个一半于输入影象( tmp)的大小。
		注意输入影象的大小(在两个方向)必须是2的冥,否则,将会显示错误。
		最后,将输入影象 tmp 更新为当前显示影象, 这样后续操作将作用于更新后的影象。
		tmp = dst;
		*/
		pyrDown(temp, dst);
		imshow(format("pyramid_up_%d", i), dst);
		temp = dst.clone();
		pyramid_images.push_back(temp);
	}
}

void USMImage(Mat src, Mat &usm, float fltPar)//图像锐化增强演算法(USM)
{
	Mat blur_img;
	/*
	USM锐化公式表示如下:
	(源图像– w*高斯模糊)/(1-w);其中w表示权重(0.1~0.9),默认为0.6
	OpenCV中的代码实现步骤
	– 高斯模糊
	– 权重叠加
	– 输出结果
	*/
	GaussianBlur(src, blur_img, Size(0, 0), 25);
	addWeighted(src, (1 + fltPar), blur_img, (fltPar*-1), 0, usm);//原图 : 模糊图片= 1.5 : -0.5 的比例进行混合
	imshow("usm", usm);
	showHistogram(usm, "Histogram_input_usm");
}

void blur_demo(Mat &image, Mat &sum)
{
	int w = image.cols;
	int h = image.rows;
	Mat result = Mat::zeros(image.size(), image.type());
	int x2 = 0, y2 = 0;
	int x1 = 0, y1 = 0;
	int ksize = 5;
	int radius = ksize / 2;
	int ch = image.channels();
	int cx = 0, cy = 0;
	for (int row = 0; row < h + radius; row++) {
		y2 = (row + 1)>h ? h : (row + 1);
		y1 = (row - ksize) < 0 ? 0 : (row - ksize);
		for (int col = 0; col < w + radius; col++) {
			x2 = (col + 1)>w ? w : (col + 1);
			x1 = (col - ksize) < 0 ? 0 : (col - ksize);
			cx = (col - radius) < 0 ? 0 : col - radius;
			cy = (row - radius) < 0 ? 0 : row - radius;
			int num = (x2 - x1)*(y2 - y1);
			for (int i = 0; i < ch; i++) {
				// 积分图查找和表,计算卷积
				int s = getblockSum(sum, x1, y1, x2, y2, i);
				result.at(cy, cx)[i] = saturate_cast(s / num);
			}
		}
	}
	imshow("blur_demo", result);
}

/**
* 3x3 sobel 垂直边缘检测演示
*/
void edge_demo(Mat &image, Mat &sum)
{
	int w = image.cols;
	int h = image.rows;
	Mat result = Mat::zeros(image.size(), CV_32SC3);
	int x2 = 0, y2 = 0;
	int x1 = 0, y1 = 0;
	int ksize = 3; // 算子大小,可以修改,越大边缘效应越明显
	int radius = ksize / 2;
	int ch = image.channels();
	int cx = 0, cy = 0;
	for (int row = 0; row < h + radius; row++) {
		y2 = (row + 1)>h ? h : (row + 1);
		y1 = (row - ksize) < 0 ? 0 : (row - ksize);
		for (int col = 0; col < w + radius; col++) {
			x2 = (col + 1)>w ? w : (col + 1);
			x1 = (col - ksize) < 0 ? 0 : (col - ksize);
			cx = (col - radius) < 0 ? 0 : col - radius;
			cy = (row - radius) < 0 ? 0 : row - radius;
			int num = (x2 - x1)*(y2 - y1);
			for (int i = 0; i < ch; i++) {
				// 积分图查找和表,计算卷积
				int s1 = getblockSum(sum, x1, y1, cx, y2, i);
				int s2 = getblockSum(sum, cx, y1, x2, y2, i);
				result.at(cy, cx)[i] = saturate_cast(s2 - s1);
			}
		}
	}
	Mat dst, gray;
	convertScaleAbs(result, dst);
	normalize(dst, dst, 0, 255, NORM_MINMAX);
	cvtColor(dst, gray, COLOR_BGR2GRAY);
	imshow("edge_demo", gray);
}

int getblockSum(Mat &sum, int x1, int y1, int x2, int y2, int i) {
	int tl = sum.at(y1, x1)[i];
	int tr = sum.at(y2, x1)[i];
	int bl = sum.at(y1, x2)[i];
	int br = sum.at(y2, x2)[i];
	int s = (br - bl - tr + tl);
	return s;
}

void add_gaussian_noise(Mat &image)//高斯杂讯
{
	Mat noise = Mat::zeros(image.size(), image.type());
	// 产生高斯噪声
	randn(noise, (15, 15, 15), (30, 30, 30));
	Mat dst;
	add(image, noise, dst);
	image = dst.clone();//dst.copyTo(image);//图像复制
						//imshow("gaussian_noise", dst);
}

void add_salt_pepper_noise(Mat &image)//白杂讯
{
	// 随机数产生器
	RNG rng(12345);
	for (int i = 0; i < 1000; ++i) {
		int x = rng.uniform(0, image.rows);
		int y = rng.uniform(0, image.cols);
		if (i % 2 == 1) {
			image.at(y, x) = Vec3b(255, 255, 255);
		}
		else {
			image.at(y, x) = Vec3b(0, 0, 0);
		}
	}
	//imshow("saltp_epper", image);
}

void blur3x3(Mat &src, Mat *det)
{
	// 3x3 均值模糊,自定义版本实现
	for (int row = 1; row < src.rows - 1; row++) {
		for (int col = 1; col < src.cols - 1; col++) {
			Vec3b p1 = src.at(row - 1, col - 1);
			Vec3b p2 = src.at(row - 1, col);
			Vec3b p3 = src.at(row - 1, col + 1);
			Vec3b p4 = src.at(row, col - 1);
			Vec3b p5 = src.at(row, col);
			Vec3b p6 = src.at(row, col + 1);
			Vec3b p7 = src.at(row + 1, col - 1);
			Vec3b p8 = src.at(row + 1, col);
			Vec3b p9 = src.at(row + 1, col + 1);

			int b = p1[0] + p2[0] + p3[0] + p4[0] + p5[0] + p6[0] + p7[0] + p8[0] + p9[0];
			int g = p1[1] + p2[1] + p3[1] + p4[1] + p5[1] + p6[1] + p7[1] + p8[1] + p9[1];
			int r = p1[2] + p2[2] + p3[2] + p4[2] + p5[2] + p6[2] + p7[2] + p8[2] + p9[2];

			det->at(row, col)[0] = saturate_cast(b / 9);
			det->at(row, col)[1] = saturate_cast(g / 9);
			det->at(row, col)[2] = saturate_cast(r / 9);
		}
	}
}

void backProjection_demo(Mat &image, Mat &model)//反向投影
{
	Mat image_hsv, model_hsv;
	cvtColor(image, image_hsv, COLOR_BGR2HSV);//彩色转HSV
	cvtColor(model, model_hsv, COLOR_BGR2HSV);

	// 定义直方图参数与属性
	int h_bins = 32, s_bins = 32;
	int histSize[] = { h_bins, s_bins };//要切分的像素强度值范围,预设为256。每个channel皆可指定一个范围。例如,[32,32,32] 表示RGB三个channels皆切分为32区段
	float h_ranges[] = { 0, 180 }, s_ranges[] = { 0, 256 };
	const float* ranges[] = { h_ranges, s_ranges };
	int channels[] = { 0, 1 };

	Mat roiHist;//计算ROI的直方图
	calcHist(&model_hsv, 1, channels, Mat(), roiHist, 2, histSize, ranges);
	normalize(roiHist, roiHist, 0, 255, NORM_MINMAX, -1, Mat());

	Mat roiproj, backproj;
	calcBackProject(&image_hsv, 1, channels, roiHist, roiproj, ranges);//使用反向投影 产生ROI(前景)的mask
	bitwise_not(roiproj, backproj);//产生背景的mask
	imshow("ROIProj", roiproj);
	imshow("BackProj", backproj);
}

void showHistogram(InputArray src, cv::String StrTitle)//直方图
{
	bool blnGray = false;
	if (src.channels() == 1)
	{
		blnGray = true;
	}

	// 三通道/单通道 直方图 纪录阵列
	vector bgr_plane;
	vector gray_plane;

	// 定义参数变量
	const int channels[1] = { 0 };
	const int bins[1] = { 256 };
	float hranges[2] = { 0, 255 };
	const float *ranges[1] = { hranges };
	Mat b_hist, g_hist, r_hist, hist;
	// 计算三通道直方图
	/*
	void calcHist( const Mat* images, int nimages,const int* channels, InputArray mask,OutputArray hist, int dims, const int* histSize,const float** ranges, bool uniform=true, bool accumulate=false );
	1.输入的图像数组
	2.输入数组的个数
	3.通道数
	4.掩码
	5.直方图
	6.直方图维度
	7.直方图每个维度的尺寸数组
	8.每一维数组的范围
	9.直方图是否是均匀
	10.配置阶段不清零
	*/
	if (blnGray)
	{
		split(src, gray_plane);
		calcHist(&gray_plane[0], 1, 0, Mat(), hist, 1, bins, ranges);
	}
	else
	{
		split(src, bgr_plane);
		calcHist(&bgr_plane[0], 1, 0, Mat(), b_hist, 1, bins, ranges);
		calcHist(&bgr_plane[1], 1, 0, Mat(), g_hist, 1, bins, ranges);
		calcHist(&bgr_plane[2], 1, 0, Mat(), r_hist, 1, bins, ranges);
	}

	/*
	* 显示直方图
	*/
	int hist_w = 512;
	int hist_h = 400;
	int bin_w = cvRound((double)hist_w / bins[0]);
	Mat histImage = Mat::zeros(hist_h, hist_w, CV_8UC3);
	// 归一化直方图数据
	if (blnGray)
	{
		normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, -1);
	}
	else
	{
		normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1);
		normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1);
		normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1);
	}

	// 绘制直方图曲线
	for (int i = 1; i < bins[0]; ++i)
	{
		if (blnGray)
		{
			line(histImage, Point(bin_w * (i - 1), hist_h - cvRound(hist.at(i - 1))),
				Point(bin_w * (i), hist_h - cvRound(hist.at(i))), Scalar(255, 255, 255),
				2, 8, 0);
		}
		else
		{
			line(histImage, Point(bin_w * (i - 1), hist_h - cvRound(b_hist.at(i - 1))),
				Point(bin_w * (i), hist_h - cvRound(b_hist.at(i))), Scalar(255, 0, 0),
				2, 8, 0);
			line(histImage, Point(bin_w * (i - 1), hist_h - cvRound(g_hist.at(i - 1))),
				Point(bin_w * (i), hist_h - cvRound(g_hist.at(i))), Scalar(0, 255, 0),
				2, 8, 0);
			line(histImage, Point(bin_w * (i - 1), hist_h - cvRound(r_hist.at(i - 1))),
				Point(bin_w * (i), hist_h - cvRound(r_hist.at(i))), Scalar(0, 0, 255),
				2, 8, 0);
		}


	}
	imshow(StrTitle, histImage);
}


Python

import cv2 as cv
import numpy as np

src = cv.imread("D:/images/cross.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

# 图像二值化
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)

# 击中击不中
se = cv.getStructuringElement(cv.MORPH_CROSS, (11, 11), (-1, -1))
binary = cv.morphologyEx(binary, cv.MORPH_HITMISS, se)


cv.imshow("black hat", binary)
cv.imwrite("D:/binary2.png", binary)

cv.waitKey(0)
cv.destroyAllWindows()


★结果图:

★延伸说明/重点回顾:


相关文章