[PYTHON] Wavelet transform of images with PyWavelets and OpenCV

Thing you want to do

I recently started learning image processing I was thinking that I would like to perform wavelet transform on the image, I found the following great article.

Mokemokechicken: Wavelet transform sample of image with Python

However, as the article author mokemokechicken also states. ** There was a problem that "it will not work unless the vertical and horizontal sizes of the images are the same" **.

So, this time, while referring to the sample code of mokemokechicken, By loading an image with OpenCV, ** "regardless of the vertical and horizontal size of the input image" ** wavelet transform to the image is possible. (Although it is written coolly, it is a punch line that I was able to do it well if I wanted to read the image with OpenCV and tampered with the code)

Things necessary

・ PyWavelets ・ Numpy ・ OpenCV

A brief description of PyWavelets

URL : http://www.pybytes.com/pywavelets/ref/2d-dwt-and-idwt.html

By using a function called * pywt.dwt2 *, for a two-dimensional array (this time an image) Two-dimensional wavelet transform can be done easily,

A function that has been extended to enable multi-level two-dimensional wavelet transform It is prepared as * pywt.wavedec2 *, and this time I dealt with this function.

Sample code

This time we are doing wavelet transform for lena

import pywt
import numpy as np
import cv2

def image_normalization(src_img):
    """
Normalization process to prevent overexposure
    cv2.Required when displaying wavelet-converted images with imshow (only for images with large values)
    """
    norm_img = (src_img - np.min(src_img)) / (np.max(src_img) - np.min(src_img))
    return norm_img

def merge_images(cA, cH_V_D):
    """numpy.4 array(upper left,(Upper right, lower left, lower right))Connect"""
    cH, cV, cD = cH_V_D
    cH = image_normalization(cH) #Even if you remove it, it's ok
    cV = image_normalization(cV) #Even if you remove it, it's ok
    cD = image_normalization(cD) #Even if you remove it, it's ok
    cA = cA[0:cH.shape[0], 0:cV.shape[1]] #If the original image is not a power of 2, there may be fractions, so adjust the size. Match the smaller one.
    return np.vstack((np.hstack((cA,cH)), np.hstack((cV, cD)))) #Attach pixels at top left, top right, bottom left, bottom right

def coeffs_visualization(cof):
    norm_cof0 = cof[0]
    norm_cof0 = image_normalization(norm_cof0) #Even if you remove it, it's ok
    merge = norm_cof0
    for i in range(1, len(cof)):
        merge = merge_images(merge, cof[i])  #Match the four images
    cv2.imshow('', merge)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def wavelet_transform_for_image(src_image, level, M_WAVELET="db1", mode="sym"):
    data = src_image.astype(np.float64)
    coeffs = pywt.wavedec2(data, M_WAVELET, level=level, mode=mode)
    return coeffs

if __name__ == "__main__":

    filename = 'lena.jpg'
    LEVEL = 3

    # 'haar', 'db', 'sym' etc...
    # URL: http://pywavelets.readthedocs.io/en/latest/ref/wavelets.html
    MOTHER_WAVELET = "db1"

    im = cv2.imread(filename)

    print('LEVEL :', LEVEL)
    print('MOTHER_WAVELET', MOTHER_WAVELET)
    print('original image size: ', im.shape)

    """
Convert for each BGR channel
    cv2.imread is B,G,Note that the images are spit out in the order of R.
    """
    B = 0
    G = 1
    R = 2
    coeffs_B = wavelet_transform_for_image(im[:, :, B], LEVEL, M_WAVELET=MOTHER_WAVELET)
    coeffs_G = wavelet_transform_for_image(im[:, :, G], LEVEL, M_WAVELET=MOTHER_WAVELET)
    coeffs_R = wavelet_transform_for_image(im[:, :, R], LEVEL, M_WAVELET=MOTHER_WAVELET)

    coeffs_visualization(coeffs_B)
    # coeffs_visualization(coeffs_G)
    # coeffs_visualization(coeffs_R)

Execution result

Original image (lena.jpg) lena のコピー.jpg

Image of wavelet coefficient (B channel) スクリーンショット 2017-04-09 18.43.08.png

Finally

If you have any corrections, please let us know.

Recommended Posts

Wavelet transform of images with PyWavelets and OpenCV
Capturing images with Pupil, python and OpenCV
Display embedded images of mp3 and flac with mutagen
Try projective transformation of images using OpenCV with Python
Create a batch of images and inflate with ImageDataGenerator
I tried "morphology conversion" of images with Python + OpenCV
Separate color images into RGB images and display them with OpenCV
The story of displaying images with OpenCV or PIL (only)
Environment construction of python and opencv
Shining life with Python and OpenCV
Neural network with OpenCV 3 and Python 3
Load gif images with Python + OpenCV
Coexistence of Python2 and 3 with CircleCI (1.0)
Draw shapes with OpenCV and PIL
Upload and download images with falcon
Basic study of OpenCV with Python
Aligning scanned images of animated video paper using OpenCV and Python
[Python] Try to recognize characters from images with OpenCV and pyocr
Drawing with Bezier curve and Fourier transform
Multi-class, multi-label classification of images with pytorch
Import of japandas with pandas 1.0 and above
Get images of OpenStreetMap and Geographical Survey Institute maps with Python + py-staticmaps
How to put OpenCV in Raspberry Pi and easily collect images of face detection results with Python
Automatically generate images of koalas and bears
Transcription of images with GCP's Vision API
[python, openCV] base64 Face recognition with images
Read the graph image with OpenCV and get the coordinates of the final point of the graph
[Python] Read images with OpenCV (for beginners)
Easy introduction of python3 series and OpenCV3
Get and estimate the shape of the head using Dlib and OpenCV with python
Importing and exporting GeoTiff images with Python
Cut out and connect images with ImageMagick
Explanation of creating an application for displaying images and drawing with Python
Examination of exchange rate forecasting method using deep learning and wavelet transform
Try to separate the background and moving object of the video with OpenCV
Hello World and face detection with OpenCV 4.3 + Python
Shuffle hundreds of thousands of images evenly with tensorflow.
Load caffe model with Chainer and classify images
Performance comparison of face detector with Python + OpenCV
Coexistence of Fcitx and Zoom ~ With Japanese localization ~
Categorize face images of anime characters with Chainer
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
Low-rank approximation of images by HOSVD and HOOI
Script to tweet with multiples of 3 and numbers with 3 !!
Noise removal and background transparency of binary images
Implementation of TRIE tree with Python and LOUDS
Data cleansing 3 Use of OpenCV and preprocessing of image data
Feature matching with OpenCV 3 and Python 3 (A-KAZE, KNN)
Continuation of multi-platform development with Electron and Python
Example of reading and writing CSV with Python
I made a program to convert images into ASCII art with Python and OpenCV
Extract images and tables from pdf with python to reduce the burden of reporting
Get media timeline images and videos with Python + Tweepy
I tried to extract features with SIFT of OpenCV
Optical Flow, the dynamics of images captured by OpenCV
Separation of Japanese surname and given name with BERT
Maximum likelihood estimation of mean and variance with TensorFlow
[OpenCV / Python] I tried image analysis of cells with OpenCV
Easy partial download of mp4 with python and youtube-dl!
Image capture / OpenCV speed comparison with and without GPU
Detect mask wearing status with OpenCV and Raspberry Pi