bool WebPEncoder::write(const Mat& img, const std::vector<int>& params) { int channels = img.channels(), depth = img.depth(); int width = img.cols, height = img.rows; const Mat *image = &img; Mat temp; size_t size = 0; bool comp_lossless = true; float quality = 100.0f; if (params.size() > 1) { if (params[0] == CV_IMWRITE_WEBP_QUALITY) { comp_lossless = false; quality = static_cast<float>(params[1]); if (quality < 1.0f) { quality = 1.0f; } if (quality > 100.0f) { comp_lossless = true; } } } uint8_t *out = NULL; if(depth != CV_8U) { return false; } if(channels == 1) { cvtColor(*image, temp, CV_GRAY2BGR); image = &temp; channels = 3; } else if (channels == 2) { return false; } if (comp_lossless) { if(channels == 3) { size = WebPEncodeLosslessBGR(image->data, width, height, image->step, &out); } else if(channels == 4) { size = WebPEncodeLosslessBGRA(image->data, width, height, image->step, &out); } } else { if(channels == 3) { size = WebPEncodeBGR(image->data, width, height, image->step, quality, &out); } else if(channels == 4) { size = WebPEncodeBGRA(image->data, width, height, image->step, quality, &out); } } if(size > 0) { if(m_buf) { m_buf->resize(size); memcpy(&(*m_buf)[0], out, size); } else { FILE *fd = fopen(m_filename.c_str(), "wb"); if(fd != NULL) { fwrite(out, size, sizeof(uint8_t), fd); fclose(fd); fd = NULL; } } } if (out != NULL) { free(out); out = NULL; } return size > 0; }
bool WebPEncoder::write(const Mat& img, const std::vector<int>& params) { CV_CheckDepthEQ(img.depth(), CV_8U, "WebP codec supports 8U images only"); const int width = img.cols, height = img.rows; bool comp_lossless = true; float quality = 100.0f; if (params.size() > 1) { if (params[0] == CV_IMWRITE_WEBP_QUALITY) { comp_lossless = false; quality = static_cast<float>(params[1]); if (quality < 1.0f) { quality = 1.0f; } if (quality > 100.0f) { comp_lossless = true; } } } int channels = img.channels(); CV_Check(channels, channels == 1 || channels == 3 || channels == 4, ""); const Mat *image = &img; Mat temp; if (channels == 1) { cvtColor(*image, temp, COLOR_GRAY2BGR); image = &temp; channels = 3; } uint8_t *out = NULL; size_t size = 0; if (comp_lossless) { if (channels == 3) { size = WebPEncodeLosslessBGR(image->ptr(), width, height, (int)image->step, &out); } else if (channels == 4) { size = WebPEncodeLosslessBGRA(image->ptr(), width, height, (int)image->step, &out); } } else { if (channels == 3) { size = WebPEncodeBGR(image->ptr(), width, height, (int)image->step, quality, &out); } else if (channels == 4) { size = WebPEncodeBGRA(image->ptr(), width, height, (int)image->step, quality, &out); } } #if WEBP_DECODER_ABI_VERSION >= 0x0206 Ptr<uint8_t> out_cleaner(out, WebPFree); #else Ptr<uint8_t> out_cleaner(out, free); #endif CV_Assert(size > 0); if (m_buf) { m_buf->resize(size); memcpy(&(*m_buf)[0], out, size); } else { FILE *fd = fopen(m_filename.c_str(), "wb"); if (fd != NULL) { fwrite(out, size, sizeof(uint8_t), fd); fclose(fd); fd = NULL; } } return size > 0; }