基於OpenCV的圖像翻轉和鏡像
點擊上方↑↑↑“OpenCV學堂”關注我
來源:公眾號 小白學視覺 授權
本期,我們將解釋如何在Python中實現圖像的鏡像或翻轉。大家只需要了解各種矩陣運算和矩陣操作背后的基本數學即可。
01. 依賴包要求
NumPy —用於矩陣運算並對其進行處理。
OpenCV —用於讀取圖像並將其轉換為2D數組(矩陣)。
Matplotlib —用於將矩陣繪制為圖像。
對於這個小型項目,我使用了著名的Lena圖像,該圖像主要用於測試計算機視覺模型。確保下載此映像並將其保存在當前工作目錄中。
import cv2
import numpy as np
from matplotlib import pyplot as plt
02. 讓我們開始吧
首先,我們使用imread()模塊中的方法讀取圖像文件cv2。為此,我們只需要導入包並使用它即可。因此,通過這樣做,我們獲得了矩陣形式的圖像。默認情況下,imread()該方法讀取的圖像BGR(Blue,Green,Red)格式。要讀取的圖像轉換為常規格式,即,RGB(Red,Green,Blue),我們使用cvtColor()來自同一模塊的方法cv2。
def read_this(image_file, gray_scale=False):
image_src = cv2.imread(image_file)
if gray_scale:
image_rgb = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
else:
image_rgb = cv2.cvtColor(image_src, cv2.COLOR_BGR2RGB)
return image_rgb
上面的函數從傳遞的圖像文件返回圖像矩陣。如果我們要獲取圖像矩陣或格式,它由常規if和else條件組成。
鏡像圖像
要基本鏡像圖像,我們需要從左到右逐行反轉矩陣。讓我們考慮一個matrix A。
>>> A = [
[
[
[
]
如果我們要鏡像此矩陣(逐行),則它將是-
[[1, 1, 4],
[0, 8, 2],
[1, 8, 3]]
我們也可以在不使用NumPy模塊的情況下執行此操作。如果是這樣,我們可以使用循環並反轉每一行。如果在圖像矩陣上執行相同的操作將花費一些時間,因為它們是非常大的矩陣,並且我們不希望我們的代碼執行得非常慢。
def mirror_this(image_file, gray_scale=False, with_plot=False):
image_rgb = read_this(image_file=image_file, gray_scale=gray_scale)
image_mirror = np.fliplr(image_rgb)
if with_plot:
fig = plt.figure(figsize=(10, 20))
ax1 = fig.add_subplot(2, 2, 1)
ax1.axis("off")
ax1.title.set_text('Original')
ax2 = fig.add_subplot(2, 2, 2)
ax2.axis("off")
ax2.title.set_text("Mirrored")
if not gray_scale:
ax1.imshow(image_rgb)
ax2.imshow(image_mirror)
else:
ax1.imshow(image_rgb, cmap='gray')
ax2.imshow(image_mirror, cmap='gray')
return True
return image_mirror
上面的函數返回一個圖像矩陣,該矩陣從左向右逐行反轉或翻轉。
讓我們繪制相同的內容-
mirror_this(image_file="lena_original.png", with_plot=True)
mirror_this(image_file="lena_original.png", gray_scale=True, with_plot=True)
翻轉圖像
要基本翻轉圖像,我們需要將矩陣從上到下逐列反轉。讓我們考慮一個matrix B。
>>> B = [
[
[
[
]
如果我們要翻轉此矩陣(按列),則它將是-
[[3, 8, 1],
[2, 8, 0],
[4, 1, 1]]
我們NumPy用於翻轉矩陣以保持代碼的牢固性。
def flip_this(image_file, gray_scale=False, with_plot=False):
image_rgb = read_this(image_file=image_file, gray_scale=gray_scale)
image_flip = np.flipud(image_rgb)
if with_plot:
fig = plt.figure(figsize=(10, 20))
ax1 = fig.add_subplot(2, 2, 1)
ax1.axis("off")
ax1.title.set_text('Original')
ax2 = fig.add_subplot(2, 2, 2)
ax2.axis("off")
ax2.title.set_text("Flipped")
if not gray_scale:
ax1.imshow(image_rgb)
ax2.imshow(image_flip)
else:
ax1.imshow(image_rgb, cmap='gray')
ax2.imshow(image_flip, cmap='gray')
return True
return image_flip
上面的函數返回一個圖像矩陣,該矩陣從上向下向下按列反轉或翻轉。
讓我們繪制相同的內容-
flip_this(image_file='lena_original.png', with_plot=True)
flip_this(image_file='lena_original.png', gray_scale=True, with_plot=True)
完整的代碼
class ImageOpsFromScratch(object):
def __init__(self, image_file):
self.image_file = image_file
def read_this(self, gray_scale=False):
image_src = cv2.imread(self.image_file)
if gray_scale:
image_rgb = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
else:
image_rgb = cv2.cvtColor(image_src, cv2.COLOR_BGR2RGB)
return image_rgb
def mirror_this(self, with_plot=True, gray_scale=False):
image_rgb = self.read_this(gray_scale=gray_scale)
image_mirror = np.fliplr(image_rgb)
if with_plot:
self.plot_it(orig_matrix=image_rgb, trans_matrix=image_mirror, head_text='Mirrored', gray_scale=gray_scale)
return None
return image_mirror
def flip_this(self, with_plot=True, gray_scale=False):
image_rgb = self.read_this(gray_scale=gray_scale)
image_flip = np.flipud(image_rgb)
if with_plot:
self.plot_it(orig_matrix=image_rgb, trans_matrix=image_flip, head_text='Flipped', gray_scale=gray_scale)
return None
return image_flip
def plot_it(self, orig_matrix, trans_matrix, head_text, gray_scale=False):
fig = plt.figure(figsize=(10, 20))
ax1 = fig.add_subplot(2, 2, 1)
ax1.axis("off")
ax1.title.set_text('Original')
ax2 = fig.add_subplot(2, 2, 2)
ax2.axis("off")
ax2.title.set_text(head_text)
if not gray_scale:
ax1.imshow(orig_matrix)
ax2.imshow(trans_matrix)
else:
ax1.imshow(orig_matrix, cmap='gray')
ax2.imshow(trans_matrix, cmap='gray')
return True
基本圖像操作包
imo = ImageOpsFromScratch(image_file='lena_original.png')
### Mirroring ###
imo.mirror_this()
imo.mirror_this(gray_scale=True)
### Flipping ###
imo.flip_this()
imo.flip_this(gray_scale=True)
將顯示以上圖像結果。現在,所有內容都已排序,我們可以創建其他圖像操作,例如equalize(),solarize()等等。

