用c++语言使用opencv将图片中指定的像素集合存到链表
时间: 2023-05-29 18:06:28 浏览: 72
以下是一个基本的示例代码,可以将图片中指定的像素集合存到链表中:
```
#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
using namespace cv;
typedef struct node {
int x;
int y;
struct node* next;
} Node;
Node* createNode(int x, int y) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->x = x;
newNode->y = y;
newNode->next = NULL;
return newNode;
}
void insertNode(Node** head, int x, int y) {
Node* newNode = createNode(x, y);
if (*head == NULL) {
*head = newNode;
}
else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
int main(int argc, char** argv) {
if (argc != 2) {
printf("Usage: ./program_name image_file\n");
return -1;
}
char* filename = argv[1];
Mat image = imread(filename, IMREAD_GRAYSCALE);
if (image.empty()) {
printf("Error: could not read image file %s\n", filename);
return -1;
}
int threshold = 128; // set threshold value for binary image
Mat binaryImage;
threshold(image, binaryImage, threshold, 255, THRESH_BINARY);
Node* head = NULL;
for (int i = 0; i < binaryImage.rows; i++) {
for (int j = 0; j < binaryImage.cols; j++) {
if (binaryImage.at<uint8_t>(i, j) == 255) {
insertNode(&head, j, i); // note the order of x and y coordinates
}
}
}
// print the coordinates stored in the linked list
printf("Coordinates of white pixels in the image:\n");
Node* current = head;
while (current != NULL) {
printf("(%d, %d)\n", current->x, current->y);
current = current->next;
}
// free the memory used by the linked list
current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```
该程序首先读取指定的图像文件,将其转换为二值图像(使用指定的阈值)并存储在 `binaryImage` 中。然后,程序遍历 `binaryImage` 中的每个像素,并将其坐标存储在链表中,如果该像素的值为 255(即白色像素)。最后,程序打印链表中存储的坐标,并释放链表的内存。
请注意,该程序需要 OpenCV 库和 C++11 标准支持。如果您正在使用 Windows 平台,则应将 `gcc` 命令替换为 `g++` 命令,并将 `#include <opencv2/opencv.hpp>` 改为 `#include <opencv2/core.hpp>` 和 `#include <opencv2/imgproc.hpp>`,并在编译时链接 OpenCV 库。