使用 OpenCV Python 將影像分割成相等的部分


Python OpenCV 庫使我們能夠利用各種影像處理工具,例如影像分類、人臉/物體檢測、跟蹤等等。

在本文中,我們將使用 python 列表切片或 numpy 陣列切片技術將影像分割成相等的部分,因為 OpenCV-python 使用 Numpy 陣列來儲存影像資料/畫素值。

輸入輸出場景

假設我們有一個輸入影像,在輸出中,我們將看到給定影像的等分部分。

方法

我們將遵循以下步驟將影像分割成相等的部分。

  • 載入影像。

  • 提取影像尺寸並將其儲存在變數中。

  • 使用 python 切片技術分割影像陣列。

  • 最後儲存分割的部分。

示例

在此示例中,我們將水平將輸入影像“cat.jpg”分成 2 部分。

import cv2
image= cv2.imread('Images/cat.jpg')

height, width, channels = image.shape
half_height = height//2

top_section = image[:half_height, :]
bottom_section = image[half_height:, :]

cv2.imshow('Top', top_section)
cv2.imshow('Bottom', bottom_section)

cv2.waitKey(0)

輸入影像

輸出影像

示例

在此示例中,我們將輸入影像“logo.png”分成 4 個相等的部分。

import cv2
import numpy as np
def divide_img_blocks(img, n_blocks=(2,2)):
   horizontal = np.array_split(img, n_blocks[0])
   splitted_img = [np.array_split(block, n_blocks[1], axis=1) for block in horizontal]
   return np.asarray(splitted_img, dtype=np.ndarray).reshape(n_blocks)

result = divide_img_blocks(cv2.imread('Images/logo.png'))

for i in range(result.shape[0]):
   for j in range(result.shape[1]):
      cv2.imwrite(f"Output Images/my_block_{i}_{j}.jpg", result[i,j])

輸入影像

輸出影像

示例

在此方法中,我們將輸入影像“Lenna.png”分成 9 個相等的部分。

import cv2,time

img = cv2.imread('Images/Lenna.png')
img2 = img

height, width, channels = img.shape
# Number of pieces Horizontally 
W_SIZE  = 3 
# Number of pieces Vertically to each Horizontal  
H_SIZE = 3

for ih in range(H_SIZE ):
   for iw in range(W_SIZE ):
   
      x = width/W_SIZE * iw 
      y = height/H_SIZE * ih
      h = (height / H_SIZE)
      w = (width / W_SIZE )
      print(x,y,h,w)
      img = img[int(y):int(y+h), int(x):int(x+w)]
      NAME = str(time.time()) 
      cv2.imwrite("Output Images/" + str(ih)+str(iw) +  ".png",img)
      img = img2

輸出

0.0 0.0 124.0 223.0
223.0 0.0 124.0 223.0
446.0 0.0 124.0 223.0
0.0 124.0 124.0 223.0
223.0 124.0 124.0 223.0
446.0 124.0 124.0 223.0
0.0 248.0 124.0 223.0
223.0 248.0 124.0 223.0
446.0 248.0 124.0 223.0

輸入影像

輸出影像

上面的示例將影像首先分成 3 個水平部分,然後對於這 3 個部分中的每一個,它將裁剪另外 3 個影像,總共留下 9 個部分。更改W_SIZEH_SIZE值以調整我們需要將影像分割成多少個相等的部分。

在以上所有示例中,我們都已成功將輸入影像分割成相等的部分。

更新於: 2023年5月30日

6K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告