# OpenCV如何實現圖片縮放與鏡像
## 一、引言
在計算機視覺和圖像處理領域,OpenCV作為開源庫被廣泛應用于各類圖像操作。圖片縮放和鏡像是基礎但關鍵的圖像變換技術,常用于數據增強、顯示適配等場景。本文將詳細介紹如何使用OpenCV實現這兩種功能。
## 二、環境準備
首先確保已安裝OpenCV庫:
```python
pip install opencv-python
導入核心庫:
import cv2
import numpy as np
img = cv2.imread('input.jpg') # 替換為實際路徑
assert img is not None, "圖片讀取失敗"
通過cv2.resize()實現,常用插值方法:
- cv2.INTER_LINEAR(雙線性插值,默認)
- cv2.INTER_NEAREST(最近鄰插值)
- cv2.INTER_CUBIC(雙三次插值)
# 縮放到原圖的50%
scale_percent = 50
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
resized_img = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)
new_size = (300, 200) # (寬度,高度)
fixed_resize = cv2.resize(img, new_size)
def aspect_ratio_resize(img, width=None, height=None):
h, w = img.shape[:2]
if width is None:
ratio = height / float(h)
dim = (int(w * ratio), height)
else:
ratio = width / float(w)
dim = (width, int(h * ratio))
return cv2.resize(img, dim)
resized_ar = aspect_ratio_resize(img, width=300)
horizontal_flip = cv2.flip(img, 1)
vertical_flip = cv2.flip(img, 0)
both_flip = cv2.flip(img, -1)
通過數組切片實現局部鏡像:
# 對圖像右半部分水平鏡像
h, w = img.shape[:2]
img[:, w//2:] = cv2.flip(img[:, w//2:], 1)
processed_img = cv2.flip(cv2.resize(img, (400,300)), 1)
def batch_process(images):
results = []
for img in images:
resized = cv2.resize(img, (224,224))
flipped = cv2.flip(resized, 1)
results.append(flipped)
return np.array(results)
插值方法選擇:
INTER_AREAINTER_CUBIC或INTER_LINEAR顏色通道問題: OpenCV默認使用BGR格式,與其他庫(如matplotlib的RGB)交互時需轉換:
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
內存管理: 大尺寸圖像處理時建議分塊操作,避免內存溢出
import cv2
# 讀取圖像
img = cv2.imread('input.jpg')
# 縮放操作
resized = cv2.resize(img, None, fx=0.5, fy=0.5)
# 鏡像操作
mirrored = cv2.flip(resized, 1)
# 保存結果
cv2.imwrite('output.jpg', mirrored)
# 顯示結果
cv2.imshow('Result', mirrored)
cv2.waitKey(0)
cv2.destroyAllWindows()
通過OpenCV的resize()和flip()函數,我們可以高效實現圖像縮放和鏡像操作。掌握這些基礎操作能為后續復雜的圖像處理任務奠定基礎。實際應用中需根據具體場景選擇合適的參數和方法,以達到最佳處理效果。
“`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。