[Python] Using OpenCV with Python (Image transformation)

resize

cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

|Method interpolation
Nearest Neighbor cv2.INTER_NEAREST
Bilinear cv2.INTER_LINEAR
Bicubic cv2.INTER_CUBIC
In [51]: rszNN = cv2.resize(I, (I.shape[1]*2, I.shape[0]*2), interpolation=cv2.INTER_NEAREST)
    ...: rszBL = cv2.resize(I, (I.shape[1]*2, I.shape[0]*2), interpolation=cv2.INTER_LINEAR)
    ...: rszBC = cv2.resize(I, (I.shape[1]*2, I.shape[0]*2), interpolation=cv2.INTER_CUBIC)

resize.png

import numpy as np
import cv2
import matplotlib.pyplot as plt

I = cv2.imread('./data/SIDBA/Lenna.bmp')

rszNN = cv2.resize(I, (I.shape[1]*2, I.shape[0]*2), interpolation=cv2.INTER_NEAREST)
rszBL = cv2.resize(I, (I.shape[1]*2, I.shape[0]*2), interpolation=cv2.INTER_LINEAR)
rszBC = cv2.resize(I, (I.shape[1]*2, I.shape[0]*2), interpolation=cv2.INTER_CUBIC)

sz  = np.array([I.shape[0],I.shape[1]])
csz = np.array([32,32])
tlpos = (sz - csz)//2
brpos = tlpos + csz

croppedNN = rszNN[tlpos[0]:brpos[0],tlpos[1]:brpos[1],:]
croppedBL = rszBL[tlpos[0]:brpos[0],tlpos[1]:brpos[1],:]
croppedBC = rszBC[tlpos[0]:brpos[0],tlpos[1]:brpos[1],:]

fig, axes = plt.subplots(ncols=3)
axes[0].imshow(croppedNN)
axes[0].set_title('nearest')
axes[0].set(adjustable='box-forced',aspect='equal')
axes[1].imshow(croppedBL)
axes[1].set_title('bilinear')
axes[1].set(adjustable='box-forced',aspect='equal')
axes[2].imshow(croppedBC)
axes[2].set_title('bicubic')
axes[2].set(adjustable='box-forced',aspect='equal')
fig.show()

rotate

If you want to rotate the center of the image to the origin, use getRotationMatrix2D and warpAffine. However, it is easier to use rotate of scipy described later.

cv2.getRotationMatrix2D(center, angle, scale)

cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]])


import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

I = cv2.imread('./data/SIDBA/Lenna.bmp')

rIntr = 15
rs = 0
re = 360

Ir = []

for r in range(rs, re+1, rIntr):
    center = (I.shape[1]*0.5,I.shape[0]*0.5)
    rotMat = cv2.getRotationMatrix2D(center, r, 1.0)    
    Irot = cv2.warpAffine(I, rotMat, (I.shape[1],I.shape[0]), flags=cv2.INTER_LINEAR)
    Ir.append(Irot)

cols = 4
rows = int(np.ceil(len(Ir) / float(cols)))

fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(3*cols,3*rows))

for idx, I in enumerate(Ir):
    r = idx // cols
    c = idx % cols
    
    title = 'rotate=%d' % (rIntr*idx)
    
    axes[r,c].imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
    axes[r,c].set_title(title)
    axes[r,c].set(adjustable='box-forced',aspect='equal')
    axes[r,c].get_xaxis().set_visible(False)
    axes[r,c].get_yaxis().set_visible(False)    

for i in range(idx+1, rows*cols):
    r = i // cols
    c = i % cols
    fig.delaxes(axes[r,c])

fig.show()

rotate_opencv.png

If the image is rectangular

image.png

scipy rotate is easy to do with scipy

scipy.ndimage.interpolation.rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3, mode='constant', cval=0.0, prefilter=True)

import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

I = cv2.imread('./data/SIDBA/Lenna.bmp')

rIntr = 15
rs = 0
re = 360

Ir = []

for r in range(rs, re+1, rIntr):
    Irot = ndimage.rotate(I, r, reshape=False)
    Ir.append(Irot)

cols = 4
rows = int(np.ceil(len(Ir) / float(cols)))

fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(3*cols,3*rows))

for idx, I in enumerate(Ir):
    r = idx // cols
    c = idx % cols
    
    title = 'rotate=%d' % (rIntr*idx)
    
    axes[r,c].imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
    axes[r,c].set_title(title)
    axes[r,c].set(adjustable='box-forced',aspect='equal')
    axes[r,c].get_xaxis().set_visible(False)
    axes[r,c].get_yaxis().set_visible(False)    

for i in range(idx+1, rows*cols):
    r = i // cols
    c = i % cols
    fig.delaxes(axes[r,c])

fig.show()

rotate_scipy.png

flip

cv2.flip(src, flipCode[, dst])

I don't know which flipCode is vertical or horizontal

flipCode = 0 ... vertical flipCode = 1 ... horizontal

You may use numpy's fliplr and flipud described later. lr means left, right, ud means up, down.


import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

I = cv2.imread('./data/SIDBA/Lenna.bmp')
Iv = cv2.flip(I, 0)
Ih = cv2.flip(I, 1)


fig, axes = plt.subplots(ncols=3, figsize=(15,10))

axes[0].imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
axes[0].set_title('original')
axes[0].set(adjustable='box-forced',aspect='equal')
axes[0].get_xaxis().set_visible(False)
axes[0].get_yaxis().set_visible(False)

axes[1].imshow(cv2.cvtColor(Iv, cv2.COLOR_BGR2RGB))
axes[1].set_title('flip vertical')
axes[1].set(adjustable='box-forced',aspect='equal')
axes[1].get_xaxis().set_visible(False)
axes[1].get_yaxis().set_visible(False)

axes[2].imshow(cv2.cvtColor(Ih, cv2.COLOR_BGR2RGB))
axes[2].set_title('flip horizontal')
axes[2].set(adjustable='box-forced',aspect='equal')
axes[2].get_xaxis().set_visible(False)
axes[2].get_yaxis().set_visible(False)

fig.show()

flip_opencv.png

numpy

numpy.fliplr(m) Horizontal flip numpy.flipud(m) Vertical flip


import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

I = cv2.imread('./data/SIDBA/Lenna.bmp')
Iv = np.flipud(I)
Ih = np.fliplr(I)


fig, axes = plt.subplots(ncols=3, figsize=(15,10))

axes[0].imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
axes[0].set_title('original')
axes[0].set(adjustable='box-forced',aspect='equal')
axes[0].get_xaxis().set_visible(False)
axes[0].get_yaxis().set_visible(False)

axes[1].imshow(cv2.cvtColor(Iv, cv2.COLOR_BGR2RGB))
axes[1].set_title('flip vertical')
axes[1].set(adjustable='box-forced',aspect='equal')
axes[1].get_xaxis().set_visible(False)
axes[1].get_yaxis().set_visible(False)

axes[2].imshow(cv2.cvtColor(Ih, cv2.COLOR_BGR2RGB))
axes[2].set_title('flip horizontal')
axes[2].set(adjustable='box-forced',aspect='equal')
axes[2].get_xaxis().set_visible(False)
axes[2].get_yaxis().set_visible(False)

fig.show()

flip_numpy.png

Recommended Posts

[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Image Filtering)
Image editing with python OpenCV
[Python] Using OpenCV with Python (Basic)
Using OpenCV with Python @Mac
[Python] Using OpenCV with Python (Edge Detection)
Try projective transformation of images using OpenCV with Python
Find image similarity with Python + OpenCV
Image processing with Python & OpenCV [Tone Curve]
Image acquisition from camera with Python + OpenCV
Light image processing with Python x OpenCV
Binarization with OpenCV / Python
Image processing with Python
I tried "smoothing" the image with Python + OpenCV
How to crop an image with Python + OpenCV
I tried "binarizing" the image with Python + OpenCV
[Small story] Test image generation with Python / OpenCV
Image processing with Python (Part 2)
"Apple processing" with OpenCV3 + Python3
[S3] CRUD with S3 using Python [Python]
Using Quaternion with Python ~ numpy-quaternion ~
Camera capture with Python + OpenCV
Sorting image files with Python (2)
Sorting image files with Python (3)
Image processing with Python (Part 1)
Tweet with image in Python
Sorting image files with Python
Image processing with Python (Part 3)
Face detection with Python + OpenCV
Get image features with OpenCV
Image recognition with Keras + OpenCV
Send using Python with Gmail
[Python] Image processing with scikit-image
[OpenCV / Python] I tried image analysis of cells with OpenCV
JPEG image generation by specifying quality with Python + OpenCV
Create miscellaneous Photoshop videos with Python + OpenCV ② Create still image Photoshop
Shining life with Python and OpenCV
Harmonic mean with Python Harmonic mean (using SciPy)
I tried "gamma correction" of the image with Python + OpenCV
Cut out an image with python
Real-time image processing basics with opencv
Image capture of firefox using python
Judgment of backlit image using OpenCV
Using Rstan from Python with PypeR
Image processing with Python 100 knocks # 3 Binarization
Easy Python + OpenCV programming with Canopy
Paste png with alpha channel as transparent image with Python / OpenCV
Let's do image scraping with Python
Try face recognition with python + OpenCV
Cut out face with Python + OpenCV
Face recognition with camera with opencv3 + python2.7
Load gif images with Python + OpenCV
Horizon processing using OpenCV morphology transformation
Notes on using rstrip with python.
Try blurring the image with opencv2
Use OpenCV with Python 3 in Window
Image processing with Python 100 knocks # 2 Grayscale
Draw an illustration with Python + OpenCV
Introduction to image analysis opencv python
Track baseball balls with Python + OpenCV
Graph Based Segmentation with Python + OpenCV