使用 OpenCV Python 将图像分成相等的部分
pythonserver side programmingprogramming
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 # 水平方向上的碎片数量 W_SIZE = 3 # 垂直方向与水平方向的碎片数量 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_SIZE 和 H_SIZE 值以调整我们需要将图像分成多少个相等的部分。
在上述所有示例中,我们已成功将输入图像分成相等的部分。