使用C++,OPENCV,OPENMP实现连通区域标记的两遍扫描算法,要求使用动态数组,最后结果以窗口显示
时间: 2024-05-03 11:21:39 浏览: 89
连通区域分析与标记代码(基于OpenCV和C++)
5星 · 资源好评率100%
以下是使用C、OpenCV和OpenMP实现连通区域标记的两遍扫描算法的示例代码。该算法会将输入的二值图像中的连通区域进行标记,并在窗口中显示结果。
```
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <opencv2/opencv.hpp>
using namespace cv;
void labelConnectComponents(Mat& input, Mat& output)
{
int rows = input.rows;
int cols = input.cols;
int label = 1;
int *labels = new int[rows * cols];
std::fill(labels, labels + rows * cols, 0);
// First pass
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (input.at<uchar>(i, j) == 255) {
int upLabel = (i == 0) ? 0 : labels[(i - 1) * cols + j];
int leftLabel = (j == 0) ? 0 : labels[i * cols + j - 1];
if (upLabel == 0 && leftLabel == 0) {
labels[i * cols + j] = label;
label++;
} else if (upLabel == 0 && leftLabel != 0) {
labels[i * cols + j] = leftLabel;
} else if (upLabel != 0 && leftLabel == 0) {
labels[i * cols + j] = upLabel;
} else {
labels[i * cols + j] = std::min(upLabel, leftLabel);
#pragma omp parallel for
for (int k = 0; k < j; k++) {
if (labels[i * cols + k] == upLabel) {
labels[i * cols + k] = labels[i * cols + j];
}
}
}
}
}
}
// Second pass
int *newLabels = new int[label];
std::fill(newLabels, newLabels + label, 0);
int newLabel = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (input.at<uchar>(i, j) == 255) {
int l = labels[i * cols + j];
if (newLabels[l] == 0) {
newLabels[l] = newLabel;
newLabel++;
}
output.at<uchar>(i, j) = newLabels[l];
}
}
}
delete[] labels;
delete[] newLabels;
}
int main(int argc, char** argv)
{
if (argc != 2) {
printf("Usage: ./program image_file\n");
return -1;
}
Mat image, gray, output;
image = imread(argv[1], IMREAD_COLOR);
if (!image.data) {
printf("No image data\n");
return -1;
}
cvtColor(image, gray, COLOR_BGR2GRAY);
threshold(gray, gray, 128, 255, THRESH_BINARY);
output.create(gray.size(), CV_8UC1);
std::fill(output.data, output.data + output.total(), 0);
double start = omp_get_wtime();
labelConnectComponents(gray, output);
double end = omp_get_wtime();
printf("Time taken: %f seconds\n", end - start);
namedWindow("Input", WINDOW_NORMAL);
namedWindow("Output", WINDOW_NORMAL);
imshow("Input", gray);
imshow("Output", output);
waitKey(0);
return 0;
}
```
阅读全文