Sample to convert image to Wavelet with Python

I became interested in wavelet transform for a while, so I actually tried to see what it was like.

Things necessary

The following three are required. Let's put it in with pip etc.

Brief commentary

Sample code

gist:image_wavelet_transform.py

image_wavelet_transform.py


# coding: utf8
# 2013/2/1 [email protected]
"""Sample script to get an image of the wavelet transform

Require: pip install PyWavelets numpy PIL

Usage: python image_wavelet_transform.py <filename> (<level>:=3) (wavelet:=db1)
"""

import sys
from PIL import Image
import pywt, numpy

filename = sys.argv[1]
LEVEL = len(sys.argv) > 2 and int(sys.argv[2]) or 3
WAVLET = len(sys.argv) > 3 and sys.argv[3] or "db1"


def merge_images(cA, cH_V_D):
    """numpy.4 array(upper left,(Upper right, lower left, lower right))Stick"""
    cH, cV, cD = cH_V_D
    print cA.shape, cH.shape, cV.shape, cD.shape
    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 numpy.vstack((numpy.hstack((cA,cH)), numpy.hstack((cV, cD)))) #Attach pixels at top left, top right, bottom left, bottom right

def create_image(ary):
    """numpy.Convert array to Grayscale image"""
    newim = Image.new("L", ary.shape)
    newim.putdata(ary.flatten())
    return newim

def wavlet_transform_to_image(gray_image, level, wavlet="db1", mode="sym"):
    """Wavelet transform gray image for level hierarchy and return each stage as image representation

    return [Restore level 0 image,Restore level 1 image,... ,Restore level<level-1>Image of, 各2D係数を1枚Image ofにした画像]
    """
    ret = []
    data = numpy.array(list(gray_image.getdata()), dtype=numpy.float64).reshape(gray_image.size)
    images = pywt.wavedec2(data, wavlet, level=level, mode=mode) # http://www.pybytes.com/pywavelets/ref/2d-dwt-and-idwt.html
    for i in range(2, len(images)+1): #Partially restore and pack in ret
        ary = pywt.waverec2(images[0:i], WAVLET)  * 2**(i-1) / 2**level #The added value is not returned when partially restored(It becomes whitish)So adjust
        ret.append(create_image(ary))
    #Make each 2D coefficient into one image
    merge = images[0] / (2**level) #Values are added to the cA part, so take the average for image display.
    for i in range(1, len(images)): 
        merge = merge_images(merge, images[i]) #Match the four images
    ret.append(create_image(merge))
    return ret

if __name__ == "__main__":
    im = Image.open(filename)
    if im.size[0] != im.size[1]: #If the vertical and horizontal sizes are not the same, something will not work, so I will match it for the time being
        max_size = max(im.size)
        newim = Image.new(im.mode, (max_size, max_size))
        newim.paste(im, (0,0))
        im = newim

    im.getdata() #If you don't call this, for some reason the next split()Fails ...? why?
    bands = im.split() #Process for each RGB channel
    converted_bands_array = [wavlet_transform_to_image(gray, LEVEL, wavlet=WAVLET) for gray in bands] #Convert for each RGB channel
    # zip(*hoge)Is difficult to understand, but converted_For bands(R,G,B)Image of(PIL.Image)Enter.Restore to RGB image with merge
    converted_array = [Image.merge(im.mode, converted_bands) for converted_bands in zip(*converted_bands_array)]

    # converted_array: [Restore level 0 image,Restore level 1 image,... ,Restore level<level-1>Image of, 各2D係数を1枚Image ofにした画像]
    for i, img in enumerate(converted_array): 
        img.save("%s_%d.png " % (filename, i)) #Appropriate image output

Execution result example

Original image (kuma_005.jpg) kuma_005.jpg

Image of coefficient imaged (level = 5) (kuma_005.jpg_5.png) kuma_005.jpg_5.png

Recommended Posts

Sample to convert image to Wavelet with Python
Convert PDF to image (JPEG / PNG) with Python
Convert the image in .zip to PDF with Python
Workflow to convert formula (image) to python
Convert list to DataFrame with python
Convert PDF to image with ImageMagick
Convert memo at once with Python 2to3
HTML email with image to send with python
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Convert 202003 to 2020-03 with pandas
Image processing with Python
Convert PDFs to images in bulk with Python
Convert svg file to png / ico with Python
How to crop an image with Python + OpenCV
Convert Windows epoch values to date with python
Sample to send slack notification with python lambda
Post an article with an image to WordPress with Python
Convert strings to character-by-character list format with python
I want to convert an image to WebP with lollipop
Image processing with Python (Part 2)
Sample data created with python
Connect to BigQuery with Python
[python] Convert date to string
Convert numpy int64 to python int
Image editing with python OpenCV
Connect to Wikipedia with Python
Post to slack with Python 3
Sorting image files with Python (2)
Sorting image files with Python (3)
Image processing with Python (Part 1)
How to convert JSON file to CSV file with Python Pandas
Tweet with image in Python
Sorting image files with Python
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Image processing with Python (Part 3)
PyInstaller memorandum Convert Python [.py] to [.exe] with 2 lines
Switch python to 2.7 with alternatives
Write to csv with Python
Convert python 3.x code to python 2.x
[Python] Image processing with scikit-image
I tried to find the entropy of the image with python
Python sample to learn XOR with genetic algorithm with neural network
[Ev3dev] How to display bmp image on LCD with python
Convert images to sepia toning with PIL (Python Imaging Library)
[Let's play with Python] Image processing to monochrome and dots
Convert video to black and white with ffmpeg + python + opencv
Convert .ipynb to .html (with BatchFile)
Python: How to use async with
[Python] Using OpenCV with Python (Image Filtering)
Link to get started with python
Convert markdown to PDF in Python
[Python] Write to csv file with Python
[Python] Using OpenCV with Python (Image transformation)
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python