This code is based on https://github.com/prasannatsm/opencv code.
authorAoD314 <morozov.andrey.vmk@gmail.com>
Thu, 7 Mar 2013 15:29:19 +0000 (19:29 +0400)
committerAoD314 <morozov.andrey.vmk@gmail.com>
Mon, 11 Mar 2013 07:51:38 +0000 (11:51 +0400)
- added webp (lossy and lossless without alpha channel)
- added tests

CMakeLists.txt
cmake/OpenCVFindLibsGrfmt.cmake
cmake/OpenCVFindWebP.cmake [new file with mode: 0644]
modules/highgui/CMakeLists.txt
modules/highgui/include/opencv2/highgui/highgui_c.h
modules/highgui/src/grfmt_webp.cpp [new file with mode: 0644]
modules/highgui/src/grfmt_webp.hpp [new file with mode: 0644]
modules/highgui/src/grfmts.hpp
modules/highgui/src/loadsave.cpp

index 99215d5..3771f74 100644 (file)
@@ -124,6 +124,7 @@ OCV_OPTION(WITH_GTK            "Include GTK support"                         ON
 OCV_OPTION(WITH_IPP            "Include Intel IPP support"                   OFF  IF (MSVC OR X86 OR X86_64) )
 OCV_OPTION(WITH_JASPER         "Include JPEG2K support"                      ON   IF (NOT IOS) )
 OCV_OPTION(WITH_JPEG           "Include JPEG support"                        ON   IF (NOT IOS) )
+OCV_OPTION(WITH_WEBP           "Include WebP support"                        ON   IF (NOT IOS) )
 OCV_OPTION(WITH_OPENEXR        "Include ILM support via OpenEXR"             ON   IF (NOT IOS) )
 OCV_OPTION(WITH_OPENGL         "Include OpenGL support"                      OFF  IF (NOT ANDROID AND NOT APPLE) )
 OCV_OPTION(WITH_OPENNI         "Include OpenNI support"                      OFF  IF (NOT ANDROID AND NOT IOS) )
@@ -636,6 +637,13 @@ if(WITH_JPEG)
 else()
   status("    JPEG:"       "NO")
 endif()
+
+if(WITH_WEBP)
+  status("    WEBP:"       WEBP_FOUND    THEN "${WEBP_LIBRARY} (ver ${WEBP_VERSION})"        ELSE "build (ver ${WEBP_VERSION})")
+else()
+  status("    WEBP:"       "NO")
+endif()
+
 if(WITH_PNG)
   status("    PNG:"        PNG_FOUND     THEN "${PNG_LIBRARY} (ver ${PNG_VERSION})"              ELSE "build (ver ${PNG_VERSION})")
 else()
index 5988169..501f8ff 100644 (file)
@@ -86,6 +86,41 @@ endif()
 
 ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION)
 
+# --- libwebp (optional) ---
+
+if(WITH_WEBP)
+  if(BUILD_WEBP)
+    ocv_clear_vars(WEBP_FOUND WEBP_LIBRARY WEBP_LIBRARIES WEBP_INCLUDE_DIR)
+  else()
+    include(cmake/OpenCVFindWebP.cmake)
+  endif()
+endif()
+
+# --- Add libwebp to 3rdparty/libwebp and compile it if not available ---
+if(WITH_WEBP AND NOT WEBP_FOUND)
+
+  set(WEBP_LIBRARY libwebp)
+  set(WEBP_LIBRARIES ${WEBP_LIBRARY})
+
+  add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libwebp")
+  set(WEBP_INCLUDE_DIR "${${WEBP_LIBRARY}_SOURCE_DIR}")
+endif()
+
+if(NOT WEBP_VERSION AND WEBP_INCLUDE_DIR)
+  ocv_clear_vars(ENC_MAJ_VERSION ENC_MIN_VERSION ENC_REV_VERSION)
+  if(EXISTS "${WEBP_INCLUDE_DIR}/enc/vp8enci.h")
+    ocv_parse_header("${WEBP_INCLUDE_DIR}/enc/vp8enci.h" WEBP_VERSION_LINES ENC_MAJ_VERSION ENC_MIN_VERSION ENC_REV_VERSION)
+    set(WEBP_VERSION "${ENC_MAJ_VERSION}.${ENC_MIN_VERSION}.${ENC_REV_VERSION}")
+  elseif(EXISTS "${WEBP_INCLUDE_DIR}/webp/encode.h")
+    file(STRINGS "${WEBP_INCLUDE_DIR}/webp/encode.h" WEBP_ENCODER_ABI_VERSION REGEX "#define[ \t]+WEBP_ENCODER_ABI_VERSION[ \t]+([x0-9a-f]+)" )
+    if(WEBP_ENCODER_ABI_VERSION MATCHES "#define[ \t]+WEBP_ENCODER_ABI_VERSION[ \t]+([x0-9a-f]+)")
+        set(WEBP_ENCODER_ABI_VERSION "${CMAKE_MATCH_1}")
+        set(WEBP_VERSION "encoder: ${WEBP_ENCODER_ABI_VERSION}")
+    else()
+      unset(WEBP_ENCODER_ABI_VERSION)
+    endif()
+  endif()
+endif()
 
 # --- libjasper (optional, should be searched after libjpeg) ---
 if(WITH_JASPER)
@@ -160,4 +195,4 @@ endif()
 #cmake 2.8.2 bug - it fails to determine zlib version
 if(ZLIB_FOUND)
   ocv_parse_header2(ZLIB "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_VERSION)
-endif()
\ No newline at end of file
+endif()
diff --git a/cmake/OpenCVFindWebP.cmake b/cmake/OpenCVFindWebP.cmake
new file mode 100644 (file)
index 0000000..740e985
--- /dev/null
@@ -0,0 +1,33 @@
+#=============================================================================
+# Find WebP library
+#=============================================================================
+# Find the native WebP headers and libraries.
+#
+#  WEBP_INCLUDE_DIRS - where to find webp/decode.h, etc.
+#  WEBP_LIBRARIES    - List of libraries when using webp.
+#  WEBP_FOUND        - True if webp is found.
+#=============================================================================
+
+# Look for the header file.
+
+unset(WEBP_FOUND)
+
+FIND_PATH(WEBP_INCLUDE_DIR NAMES webp/decode.h)
+
+if(NOT WEBP_INCLUDE_DIR)
+    unset(WEBP_FOUND)
+else()
+    MARK_AS_ADVANCED(WEBP_INCLUDE_DIR)
+
+    # Look for the library.
+    FIND_LIBRARY(WEBP_LIBRARY NAMES webp)
+    MARK_AS_ADVANCED(WEBP_LIBRARY)
+
+    # handle the QUIETLY and REQUIRED arguments and set WEBFOUND_FOUND to TRUE if
+    # all listed variables are TRUE
+    INCLUDE(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
+    FIND_PACKAGE_HANDLE_STANDARD_ARGS(WebP DEFAULT_MSG WEBP_LIBRARY WEBP_INCLUDE_DIR)
+
+    SET(WEBP_LIBRARIES ${WEBP_LIBRARY})
+    SET(WEBP_INCLUDE_DIRS ${WEBP_INCLUDE_DIR})
+endif()
index f893490..4510145 100644 (file)
@@ -20,6 +20,12 @@ if(WITH_JPEG)
   list(APPEND GRFMT_LIBS ${JPEG_LIBRARIES})
 endif()
 
+if(WITH_WEBP)
+  add_definitions(-DHAVE_WEBP)
+  ocv_include_directories(${WEBP_INCLUDE_DIR})
+  list(APPEND GRFMT_LIBS ${WEBP_LIBRARIES})
+endif()
+
 if(WITH_PNG)
   add_definitions(-DHAVE_PNG)
   add_definitions(${PNG_DEFINITIONS})
index 9c7166f..116e8c1 100644 (file)
@@ -223,7 +223,8 @@ enum
     CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2,
     CV_IMWRITE_PNG_STRATEGY_RLE =3,
     CV_IMWRITE_PNG_STRATEGY_FIXED =4,
-    CV_IMWRITE_PXM_BINARY =32
+    CV_IMWRITE_PXM_BINARY =32,
+    CV_IMWRITE_WEBP_QUALITY =64
 };
 
 /* save image to file */
diff --git a/modules/highgui/src/grfmt_webp.cpp b/modules/highgui/src/grfmt_webp.cpp
new file mode 100644 (file)
index 0000000..b2722cc
--- /dev/null
@@ -0,0 +1,253 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                           License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
+// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's in binary form must reproduce the above copyright notice,
+//     this list of conditions and the following disclaimer in the documentation
+//     and/or other materials provided with the distribution.
+//
+//   * The name of the copyright holders may not be used to endorse or promote products
+//     derived from this software without specific prior written permission.
+//
+// This software is provided by the copyright holders and contributors "as is" and
+// any express or implied warranties, including, but not limited to, the implied
+// warranties of merchantability and fitness for a particular purpose are disclaimed.
+// In no event shall the Intel Corporation or contributors be liable for any direct,
+// indirect, incidental, special, exemplary, or consequential damages
+// (including, but not limited to, procurement of substitute goods or services;
+// loss of use, data, or profits; or business interruption) however caused
+// and on any theory of liability, whether in contract, strict liability,
+// or tort (including negligence or otherwise) arising in any way out of
+// the use of this software, even if advised of the possibility of such damage.
+//
+//M*/
+
+#ifdef HAVE_WEBP
+
+#include "precomp.hpp"
+
+#include <webp/decode.h>
+#include <webp/encode.h>
+#include <stdio.h>
+#include <limits.h>
+
+#include "grfmt_webp.hpp"
+
+#include "opencv2/imgproc/imgproc.hpp"
+
+namespace cv
+{
+
+WebPDecoder::WebPDecoder()
+{
+    m_signature = "RIFF....WEBPVP8 ";
+    m_buf_supported = true;
+}
+
+WebPDecoder::~WebPDecoder()
+{
+}
+
+ImageDecoder WebPDecoder::newDecoder() const
+{
+    return new WebPDecoder;
+}
+
+bool WebPDecoder::checkSignature( const std::string& signature ) const
+{
+    size_t len = signatureLength();
+    bool ret = false;
+
+    if(signature.size() >= len)
+    {
+        ret = ( (memcmp(signature.c_str(), m_signature.c_str(), 4) == 0) &&
+            (memcmp(signature.c_str() + 8, m_signature.c_str() + 8, 4) == 0) );
+    }
+
+    return ret;
+}
+
+bool WebPDecoder::readHeader()
+{
+    if (m_buf.empty())
+    {
+        FILE * wfile = NULL;
+
+        wfile = fopen(m_filename.c_str(), "rb");
+
+        if(wfile == NULL)
+        {
+            return false;
+        }
+
+        fseek(wfile, 0, SEEK_END);
+        size_t wfile_size = ftell(wfile);
+        fseek(wfile, 0, SEEK_SET);
+
+        if(wfile_size > (size_t)INT_MAX)
+        {
+            fclose(wfile);
+            return false;
+        }
+
+        data.create(1, (int)wfile_size, CV_8U);
+
+        size_t data_size = fread(data.data, 1, wfile_size, wfile);
+
+        if(wfile)
+        {
+            fclose(wfile);
+        }
+
+        if( data_size < wfile_size )
+        {
+            return false;
+        }
+    }
+    else
+    {
+        data = m_buf;
+    }
+
+    if(WebPGetInfo(data.data, data.total(), &m_width, &m_height) == 1)
+    {
+        m_type = CV_8UC3;
+        return true;
+    }
+
+    return false;
+}
+
+bool WebPDecoder::readData(Mat &img)
+{
+    if( m_width > 0 && m_height > 0 )
+    {
+        uchar* out_data = img.data;
+        unsigned int out_data_size = m_width * m_height * 3 * sizeof(uchar);
+
+        uchar *res_ptr = WebPDecodeBGRInto(data.data, data.total(), out_data, out_data_size, m_width * 3);
+
+        if(res_ptr == out_data)
+        {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+WebPEncoder::WebPEncoder()
+{
+    m_description = "WebP files (*.webp)";
+    m_buf_supported = true;
+}
+
+WebPEncoder::~WebPEncoder()
+{
+}
+
+ImageEncoder WebPEncoder::newEncoder() const
+{
+    return new WebPEncoder();
+}
+
+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;
+    int size = 0;
+
+    bool comp_lossless = true;
+    int quality = 100;
+
+    if (params.size() > 1)
+    {
+        if (params[0] == CV_IMWRITE_WEBP_QUALITY)
+        {
+            comp_lossless = false;
+            quality = params[1];
+            if (quality < 1)
+            {
+                quality = 1;
+            }
+            if (quality > 100)
+            {
+                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;
+    }
+
+    if (comp_lossless)
+    {
+        size = WebPEncodeLosslessBGR(image->data, width, height, ((width * 3 + 3) & ~3), &out);
+    }
+    else
+    {
+        size = WebPEncodeBGR(image->data, width, height, ((width * 3 + 3) & ~3), (float)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;
+}
+
+}
+
+#endif
diff --git a/modules/highgui/src/grfmt_webp.hpp b/modules/highgui/src/grfmt_webp.hpp
new file mode 100644 (file)
index 0000000..15033d1
--- /dev/null
@@ -0,0 +1,86 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                           License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
+// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's in binary form must reproduce the above copyright notice,
+//     this list of conditions and the following disclaimer in the documentation
+//     and/or other materials provided with the distribution.
+//
+//   * The name of the copyright holders may not be used to endorse or promote products
+//     derived from this software without specific prior written permission.
+//
+// This software is provided by the copyright holders and contributors "as is" and
+// any express or implied warranties, including, but not limited to, the implied
+// warranties of merchantability and fitness for a particular purpose are disclaimed.
+// In no event shall the Intel Corporation or contributors be liable for any direct,
+// indirect, incidental, special, exemplary, or consequential damages
+// (including, but not limited to, procurement of substitute goods or services;
+// loss of use, data, or profits; or business interruption) however caused
+// and on any theory of liability, whether in contract, strict liability,
+// or tort (including negligence or otherwise) arising in any way out of
+// the use of this software, even if advised of the possibility of such damage.
+//
+//M*/
+
+#ifndef _GRFMT_WEBP_H_
+#define _GRFMT_WEBP_H_
+
+#include "grfmt_base.hpp"
+
+#ifdef HAVE_WEBP
+
+namespace cv
+{
+
+class WebPDecoder : public BaseImageDecoder
+{
+public:
+
+    WebPDecoder();
+    ~WebPDecoder();
+
+    bool readData( Mat& img );
+    bool readHeader();
+    void close();
+    bool checkSignature( const std::string& signature ) const;
+
+    ImageDecoder newDecoder() const;
+
+protected:
+    Mat data;
+};
+
+class WebPEncoder : public BaseImageEncoder
+{
+public:
+    WebPEncoder();
+    ~WebPEncoder();
+
+    bool write(const Mat& img, const std::vector<int>& params);
+
+    ImageEncoder newEncoder() const;
+};
+
+}
+
+#endif
+
+#endif /* _GRFMT_WEBP_H_ */
index 8dddf0d..659ceb7 100644 (file)
@@ -51,5 +51,6 @@
 #include "grfmt_png.hpp"
 #include "grfmt_jpeg2000.hpp"
 #include "grfmt_exr.hpp"
+#include "grfmt_webp.hpp"
 
 #endif/*_GRFMTS_H_*/
index 00ae49d..a27f339 100644 (file)
@@ -64,6 +64,10 @@ struct ImageCodecInitializer
         decoders.push_back( new JpegDecoder );
         encoders.push_back( new JpegEncoder );
     #endif
+    #ifdef HAVE_WEBP
+        decoders.push_back( new WebPDecoder );
+        encoders.push_back( new WebPEncoder );
+    #endif
         decoders.push_back( new SunRasterDecoder );
         encoders.push_back( new SunRasterEncoder );
         decoders.push_back( new PxMDecoder );