#include <opencv2/opencv.hpp>
#include <fstream>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <./opencv2/highgui/highgui_c.h>
#include <stdio.h>
using namespace std;
using namespace cv;
const int width = 1000;
const int height = 1500;
const int framesize = width * height * 3 / 2;
int main()
{
ifstream fin("demo.yuv", ios_base::in | ios_base::binary);
if (!fin)
{
cout << "the file is error" << endl;
return -1;
}
fin.seekg(0, ios::end); // 设置文件指针到文件流的尾部
streampos ps = fin.tellg(); // 指出当前的文件指针
unsigned long fileSize = ps;
cout << "file size: " << ps << endl; // 输出指针的位置
unsigned frameCount = ps / framesize; // 帧大小
cout << "frameNumber: " << frameCount << endl; // 输出帧数
fin.close();
FILE *fileIn = fopen("demo.yuv", "rb");
if (!fileIn)
{
cout << "Error opening file." << endl;
return -1;
}
// 分配足够的内存来存储整个 YUV 帧
unsigned char *pYuvBuf = new unsigned char[framesize];
// 创建窗口
namedWindow("yuv", WINDOW_NORMAL);
// 循环读取每一帧
for (int i = 0; i < frameCount; ++i)
{
// 读取整个 YUV 帧
if (fread(pYuvBuf, 1, framesize, fileIn) != framesize)
{
cout << "Error reading YUV data." << endl;
break;
}
// 创建 Mat 对象来存储 YUV 数据
cv::Mat yuvImg(height, width, CV_8UC1, pYuvBuf);
// 计算矩形的位置
int rectX = 200;
int rectY = 300;
int rectWidth = 300;
int rectHeight = 300;
// 修改 Y 分量以模拟矩形
for (int x = rectX; x < rectX + rectWidth; x++)
{
if (x < rectX + rectWidth / 3 || x > (rectX + rectWidth) - rectWidth / 3)
{
for (int y = rectY; y < rectY + rectHeight; y++)
{
if (y < rectY + rectHeight / 3 || y > (rectY + rectHeight) - rectHeight / 3)
{
if (y < rectY + 5 || y > (rectY + rectHeight) - 5 || x < rectX + 5 || x > (rectX + rectWidth) - 5)
{
// 获取 Y 分量的位置
int index = y * width + x;
// 降低 Y 分量的值以使该区域变暗
pYuvBuf[index] -= 50; // 降低亮度
}
}
}
}
}
// 设置中点
// 定义圆形的中心点和半径
int centerX = rectX + rectWidth / 2;
int centerY = rectY + rectHeight / 2;
int radius = 5;
// 遍历圆形区域内的每个像素
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// 检查当前像素是否在圆形内
if ((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY) <= radius * radius)
{
// 获取Y分量的位置
int yuvIndex = y * width + x;
// 降低亮度(例如减少50)
pYuvBuf[yuvIndex] -= 50; // 注意不要让Y分量小于0
}
}
}
// 显示 YUV 图像
imshow("yuv", yuvImg);
cvWaitKey(0);
}
// 清理资源
delete[] pYuvBuf;
fclose(fileIn);
destroyAllWindows();
return 0;
}
C++ 实现读取YUV文件并OSD叠加
最新推荐文章于 2024-08-09 17:52:08 发布