imencode与imdecode图像的编码解码用法openCV

1. 函数说明

(1) imencode

bool imencode(const String& ext, InputArray img, vector<uchar>& buf, const vector<int>& params=vector<int>())

参数:
ext-定义输出文件格式的扩展名
img-需要被编码的图像
buf-输出的缓存区,类型是vector
parms-被编码的格式和压缩率,类型是vector
prams目前支持以下参数:
JPEG,它的压缩率范围(cv_imwrite_jpeg_quality)从0到100(越大越好)。默认值是95。100为没有压缩。
对于WEBP来说,它的压缩范围(cv_imwrite_webp_quality)从1到100(越大越好)。默认情况下(不含任何参数)和质量在100以上,则使用无损压缩。
png,可以压缩级别(cv_imwrite_png_compression)从0到9。更高的值意味着更小的尺寸和更长的压缩时间。默认值是3。
PPM、PGM、或PBM,它可以是一个二进制格式的标志(cv_imwrite_pxm_binary),0或1。默认值是1。

(2) imdecode

C++: Mat imdecode(InputArray buf, int flags)
C++: Mat imdecode(InputArray buf, int flags, Mat* dst)

buf-输入解压的buf
flags-和imread()的flags是一样的
CV_LOAD_IMOSE_COLOR-如果设置,始终将图像转换为彩色图像
CV_LOAD_IMAGE_GRAYSCALE如果设置,始终将图像转换为灰度图像
dst -解码矩阵的可选输出占位符。不填则是NULL。

2. 代码示例

main.cpp

#include
 
#include
#include
 
using namespace std;
using namespace cv;
//this program is used for testing opencv encode and decode for jgeg pictures
int main()
{
    Mat tstMat=imread("/home/zhy/Documents/Perception/camera_data/lane_image/data/image/1/0000.jpg");
   // imshow("picture",tstMat);
    vector<unsigned char> inImage;
    imencode(".jpg",tstMat,inImage);
    size_t datalen=inImage.size();
    
    unsigned char *msgImage = new unsigned char[datalen];
    
    for(int i=0;i<datalen;i++)
    {
        msgImage[i]=inImage[i];
        //cout<
    }
 
    vector<unsigned char> buff;
    for(int i=0;i<datalen;i++)
    {
           buff.push_back(msgImage[i]);
    }
    Mat show=imdecode(buff,CV_LOAD_IMAGE_COLOR);
    imshow("picture",show);
 
    cv::waitKey(0);
    cout<<"hello world"<<endl;
    return 0;
}

CMakeLists.txt

# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(1) # 工程名

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
  # Add OpenCV headers location to your include paths
  include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
add_executable(main main.cpp)

# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})


执行过程
imencode与imdecode图像的编码解码用法openCV_第1张图片

imencode与imdecode图像的编码解码用法openCV_第2张图片

你可能感兴趣的:(opencv,c++,cmake)