數字視頻處理(二)——直方圖均衡化


  解決方案資源管理器界面如下:
在這裏插入圖片描述

main.cpp

#include <iostream>
#include <cstdio>
#include <fstream>
#include "YHistogram.h"

using namespace std;

#define width 500
#define height 500


int main()
{
	//讀入文件
	ifstream inYUV("seed.yuv", ios::binary);
	ofstream outYUV("HisSeed.yuv", ios::binary);
	if (!inYUV) { cout << "error to open file1!" << endl; }
	if (!outYUV) { cout << "error to open file2" << endl; }

	int TotalSize = width * height * 3;
	int YSize = width * height;
	unsigned char* in_YUV = new unsigned char[TotalSize];
	unsigned char* in_Y = new unsigned char[YSize];
	unsigned char* out_Y = new unsigned char[YSize];
	unsigned char* out_YUV = new unsigned char[TotalSize];

	inYUV.read((char*)in_YUV, TotalSize);
	
	//for (int i = 0; i < TotalSize; i++)
	//{
	//	int y = in_YUV[i];
	//}
	//提取Y分量
	EXTRACT(in_YUV, in_Y, width, height);
	
	//直方圖均衡化
	Histogram(in_Y, out_Y, width, height);
	
	//UV分量的計算
	Y2YUV(out_Y, out_YUV, width, height);
	
	//寫入YUV文件
	outYUV.write((char*)out_YUV, TotalSize);
	
	inYUV.close();
	outYUV.close();

	return 0;
}


YHistogram.h

#pragma once
void EXTRACT(unsigned char* in_YUV, unsigned char* in_Y, int width, int height);
void Histogram(unsigned char* in_Y, unsigned char* out_Y, int width, int height);
void Y2YUV(unsigned char* out_Y, unsigned char* out_YUV, int width, int height);

YHistogram.cpp

#include <iostream>
#include <cstdio>
#include "YHistogram.h"

using namespace std;

void EXTRACT(unsigned char* in_YUV, unsigned char* in_Y, int width, int height)
{
	int TotalSize = width * height * 3;
	int YSize = width * height;

	for (int i = 0; i < YSize; i++)
	{
		*(in_Y + i) = *(in_YUV + i);
	}
}

void Histogram(unsigned char* in_Y, unsigned char* out_Y, int width, int height)
{
	int TotalSize = width * height * 3;
	int YSize = width * height;
	double* count_p = new double[256];
	int* CCOUNT = new int[256];
	int* COUNT = new int[256];

	//初始化爲0
	for (int i = 0; i < 256; i++)
	{
		COUNT[i] = 0;
	}

	//進行直方圖均衡化
	
	//先計算總數
	for (int i = 0; i < YSize; i++)
	{
		int y = in_Y[i];
		COUNT[y]++;
	}

	//計算頻數
	for (int i = 0; i < 256; i++)
	{
		count_p[i] = (double)COUNT[i] / YSize;
	}

	CCOUNT[0] = int(255 * count_p[0] + 0.5);
	
	//計算累加和
	for (int i = 1; i < 256; i++)
	{
		count_p[i] = count_p[i] + count_p[i - 1];
		CCOUNT[i] = int(255 * count_p[i] + 0.5);
	}

	//進行直方圖均衡化
	for (int i = 0; i < YSize; i++)
	{
		out_Y[i] = CCOUNT[in_Y[i]];
	}
}

void Y2YUV(unsigned char* out_Y, unsigned char* out_YUV, int width, int height)
{
	int TotalSize = width * height * 3;
	int YSize = width * height;

	for (int i = 0; i < TotalSize; i++)
	{
		if (i < YSize)
		{
			out_YUV[i] = out_Y[i];
		}
		else
			out_YUV[i] = 128;
	}
}

實驗結果

處理前 處理後
在這裏插入圖片描述 在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章