📌  相关文章
📜  在Python中使用 OpenCV 将图像分成相等的部分

📅  最后修改于: 2022-05-13 01:55:17.719000             🧑  作者: Mango

在Python中使用 OpenCV 将图像分成相等的部分

在本文中,我们将看到如何在Python中使用 OpenCV 将图像分成相等的部分。我们熟悉Python列表和一维列表切片。但在图像的情况下,我们将使用 2D 列表理解,因为图像是像素强度的 2D 矩阵。

使用的图像:

Python3
import cv2
  
img = cv2.imread('img.jpg')
  
# cv2.imread() -> takes an image as an input
h, w, channels = img.shape
  
half = w//2
  
  
# this will be the first column
left_part = img[:, :half] 
  
# [:,:half] means all the rows and
# all the columns upto index half
  
# this will be the second column
right_part = img[:, half:]  
  
# [:,half:] means al the rows and all
# the columns from index half to the end
# cv2.imshow is used for displaying the image
cv2.imshow('Left part', left_part)
cv2.imshow('Right part', right_part)
  
# this is horizontal division
half2 = h//2
  
top = img[:half2, :]
bottom = img[half2:, :]
  
cv2.imshow('Top', top)
cv2.imshow('Bottom', bottom)
  
# saving all the images
# cv2.imwrite() function will save the image 
# into your pc
cv2.imwrite('top.jpg', top)
cv2.imwrite('bottom.jpg', bottom)
cv2.imwrite('right.jpg', right_part)
cv2.imwrite('left.jpg', left_part)
cv2.waitKey(0)


输出:

解释:

首先,选择一个图像作为输入并使用 cv2.imread()函数读取它。然后使用img.shape命令提取图像的尺寸,并将值分别存储到 h、w、通道中。之后对图像执行列表切片将产生所需的结果。为什么?如前所述,图像只不过是彩色像素强度的 2D 矩阵。因此,将图像分成两个或更多部分意味着基本上将矩阵切成两个或更多部分。

对于水平除法,我们需要将宽度除以 2 的因子,然后将矩阵取到该索引并将其存储在这种情况下的变量“left_part”中。它是这样的:

left_part = img[:,:w//2]

将这两个部分存储在不同的变量中后,我们使用 cv2.imshow()函数显示它们,该函数接受两个参数,第一个是图像的标题,一个字符串,第二个是要显示的图像。例子:

cv2.imshow('Title of the image', left_part)

要将生成的图像保存在计算机上,我们使用 cv2.imwrite()函数,该函数也接受两个参数,一个是字符串,另一个是要保存的图像。例子:

cv2.imwrite('name_of_the_image.jpg',left_part)

最后一个函数cv2.waitKey() 只接受一个以毫秒为单位的时间参数。 cv2.waitKey(1) 表示所有的 cv2.imshow() 将显示图像 1ms 然后将自动关闭窗口,而 cv2.waitKey(0) 将显示窗口直到无穷大,即除非用户按下退出。