使用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个部分进行裁剪,最终得到9个部分。更改 W_SIZE 和 H_SIZE 的值以调整需要将图像划分为多少个等分。
在以上所有示例中,我们成功地将输入图像分成了相等的部分。