基于图像梯度的分割方法
#ifndef BINARYIMAGEBASEDONGGRADIENT_H
#define BINARYIMAGEBASEDONGGRADIENT_H
#include
#include
#include "opencv2/opencv.hpp"
计算水平梯度函数 void CalculateHorizonGradient(const cv::Mat& srcImg, cv::Mat& horizonGradient) { 使用OpenCV库构建梯度矩阵 HorizonGradient 初始化为零矩阵 const int nCols = srcImg.cols; const int nRows = srcImg.rows; }
遍历每一行的像素数据,并对每一列进行水平梯度计算。
首先读取当前行的像素数据到srcData变量。
接着初始化水平梯度数组gradientData。
对于每一列进行处理:
对于每一列进行处理:
计算相邻两个像素之间的差值绝对值并存储到gradientData数组中。
完成水平梯度的计算过程
该函数用于计算垂直梯度并存储结果在一个名为horizonGradient的矩阵中。通过初始化一个全零矩阵来计算水平梯度,并获取图像的高度和宽度值来完成计算过程。
for循环体从i=1开始,并持续到i小于nRows-1结束。
每一步骤中提取上一行数据。
随后计算当前行与下一行之间的差异。
将这些差异值存储到梯度数据中。
完成所有列的计算后继续下一个步骤。
返回结果并结束程序。
计算阈值的浮点函数CalculateThreshold接受三个引用const的cv::Mat对象参数srcImg、gradientCol和gradientRow
const int nCols = srcImg.cols;
const int nRows = srcImg.rows;
float T = 0.0;
float denominator = 0.0;//分母
float numerator = 0.0; //分子
int gradient_max = 0;
for (int r = 0; r < nRows; r++)
{
const uchar* srcData = srcImg.ptr
const uchar* gradientColData = gradientCol.ptr
const uchar* gradientRowData = gradientRow.ptr
The code iterates over each integer variable c starting at 0 and incrementing until it reaches the value of nCols. For each iteration, it computes the maximum value between the corresponding elements of gradientColData and gradientRowData at index c, storing this result in a variable named gradient_max. The variable denominator accumulates the sum of these maximum values, while numerator is incremented by multiplying gradient_max with the element in srcData at position c.
该函数计算分子与分母的商。
该函数返回上述计算的结果。
基于梯度的二值化函数。
const cv::Mat srcImg[] {
如果源图像数据不存在,则返回false。
创建目标图像矩阵。
如果源图像是三通道,则将其转换为灰度图;否则直接复制到目标图像中。
创建二值化图像,并指定大小和类型。
}
const int nCols = srcImg.cols;
const int nRows = srcImg.rows;
// 水平方向梯度—x—列
cv::Mat gradient_x;
被用于计算水平方向梯度 image 的 x 分量。
// 垂直方向梯度—y—行
cv::Mat gradient_y;
被用于计算垂直方向梯度 image 的 y 分量。
float ThresholdValue = CalculateThreshold(image, gradient_x, gradient_y);
遍历行索引r从0到nRows-1。
获取当前行对应的图像像素数据imgData。
获取当前行对应的二进制像素数据binData。
遍历列索引c从0到nCols-1。
若图像像素值imgData[c]大于等于预先设定的阈值:
将二进制像素值binData[c]置为全白(255)。
否则:
将二进制像素值binData[c]置为黑色(0)。
循环结束后返回true。
