在 OpenCV 中,可以使用不同的编码方式对图像进行编码和解码。
常见的图像编码方式包括 JPEG、PNG、BMP 等。
下面是一些常用的 OpenCV 图像编码和解码函数:
imencode函数
cv::imencode 是 OpenCV 中用于将图像编码为指定格式的函数。
bool cv::imencode(const String &ext, InputArray img, std::vector<uchar> &buf, const std::vector<int> ¶ms = std::vector<int>())
参数说明:
- ext:表示要编码的图像格式的扩展名,例如 “.jpg”, “.png” 等。
- img:表示要编码的输入图像,可以是 cv::Mat 或 cv::UMat 对象。
- buf:表示输出的编码数据缓冲区,以
std::vector<uchar>
形式传递。 - params:表示编码过程中的可选参数,以
std::vector<int>
形式传递。根据不同的编码格式,可以指定不同的参数,例如 JPEG 的压缩质量、PNG 的压缩级别等。
imdecode函数
cv::imdecode 是 OpenCV 中用于将图像解码的函数,它可以将编码后的图像数据解码为原始图像格式。
cv::Mat cv::imdecode(const cv::InputArray &buf, int flags)
参数说明:
- buf:表示输入的图像数据缓冲区,可以是
std::vector<uchar>
或 cv::Mat。 - flags:表示解码时的标志,用于指定解码后的图像格式。可以使用 cv::IMREAD_COLOR、cv::IMREAD_GRAYSCALE 等常量来指定。
图像解码:
std::vector<uchar> encoded_data; // 编码后的图像数据
// 从文件或其他地方读取编码后的数据到 encoded_data
cv::Mat decoded_image = cv::imdecode(encoded_data, cv::IMREAD_COLOR);
if (!decoded_image.empty()) {
// 解码成功,可以对解码后的图像进行处理
// ...
}
读取图像:
cv::Mat image = cv::imread("image.jpg", cv::IMREAD_COLOR);
编码为 JPEG 格式:
std::vector<uchar> buffer;
std::vector<int> params = {cv::IMWRITE_JPEG_QUALITY, 95};
cv::imencode(".jpg", image, buffer, params);
编码为 PNG 格式:
std::vector<uchar> buffer;
std::vector<int> params = {cv::IMWRITE_PNG_COMPRESSION, 9};
cv::imencode(".png", image, buffer, params);
解码 JPEG 或 PNG 图像:
cv::Mat image = cv::imdecode(buffer, cv::IMREAD_COLOR);