利用c语言编写出与opencv中的mean函数相同功能的程序
时间: 2024-02-17 08:04:55 浏览: 27
下面是一个利用C语言编写的计算像素均值的程序,实现了与OpenCV中的mean函数相同的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
{
if ( argc != 2 )
{
printf("usage: ./mean image_file\n");
return -1;
}
Mat image;
image = imread( argv[1], 1 );
if ( !image.data )
{
printf("No image data \n");
return -1;
}
double mean_val = mean(image)[0];
printf("The mean value of pixels in the image is: %f\n", mean_val);
return 0;
}
```
该程序需要输入一张图片的文件名作为命令行参数,读取图片并计算像素均值。代码中使用了OpenCV库中的mean函数,计算出像素均值并输出。
相关问题
利用c语言编写出与opencv中的mean函数相同功能的程序,并且不使用mean函数 重新编写
下面是一个利用C语言编写的计算像素均值的程序,不使用OpenCV库中的mean函数,利用指针遍历像素进行计算,实现与OpenCV中的mean函数相同的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
{
if ( argc != 2 )
{
printf("usage: ./mean image_file\n");
return -1;
}
Mat image;
image = imread( argv[1], 1 );
if ( !image.data )
{
printf("No image data \n");
return -1;
}
int rows = image.rows;
int cols = image.cols;
int channels = image.channels();
unsigned char *data = image.data;
double sum = 0;
int count = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
for (int k = 0; k < channels; k++)
{
sum += data[i * cols * channels + j * channels + k];
count++;
}
}
}
double mean_val = sum / count;
printf("The mean value of pixels in the image is: %f\n", mean_val);
return 0;
}
```
该程序同样需要输入一张图片的文件名作为命令行参数,读取图片并计算像素均值。代码中使用了指针遍历像素,计算出像素均值并输出,实现了与OpenCV中的mean函数相同的功能。
用c语言编写一个opencv打开摄像头函数
以下是一个使用 C 语言和 OpenCV 库打开摄像头的示例代码:
```c
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
int main(int argc, char** argv) {
cv::VideoCapture cap(0); // 打开默认的摄像头
if (!cap.isOpened()) { // 检测摄像头是否成功打开
return -1;
}
cv::Mat frame;
while (true) {
cap >> frame; // 读取新帧
if (frame.empty()) { // 检测帧是否为空
break;
}
cv::imshow("Camera", frame); // 显示帧
if (cv::waitKey(30) >= 0) { // 等待 30ms 并检测按键
break;
}
}
return 0;
}
```
这个例子使用 `cv::VideoCapture` 类从默认的摄像头读取视频帧,并在循环中显示每一帧。如果用户按下任意键或关闭窗口,程序将退出循环并关闭摄像头。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)