📌  相关文章
📜  高度宽度图像 opencv - Python (1)

📅  最后修改于: 2023-12-03 15:42:32.599000             🧑  作者: Mango

高度和宽度图像 OpenCV - Python

在计算机视觉中,高度和宽度图像(或称为灰度图像或单色图像)是一种常见类型的图像。它由像素组成,每个像素具有一个灰度值,通常在0到255之间。在本次教程中,我们将介绍如何使用Python的OpenCV库来读取、显示和处理高度和宽度图像。

读取图像

要读取图像,请使用 cv2.imread()函数。该函数接受一个参数,即图像的路径。它将返回一个Numpy数组,其中包含图像的像素值。

import cv2

# Load an image
img = cv2.imread('image.jpg', 0)

# Display the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
显示图像

要显示图像,请使用 cv2.imshow()函数。该函数的第一个参数是窗口的名称,第二个参数是要显示的图像。

# Display the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
保存图像

要保存图像,请使用 cv2.imwrite()函数。该函数的第一个参数是文件的名称,第二个参数是图像的Numpy数组。

# Save the image
cv2.imwrite('new_image.jpg', img)
图像属性

高度和宽度图像有两个属性:高度和宽度。可以使用 shape属性来获取这些值。

# Get the height and width of the image
height, width = img.shape
print('Height:', height)
print('Width:', width)
图像处理

可以使用OpenCV库提供的许多函数对高度和宽度图像进行处理。以下是一些示例:

  1. 翻转图像
# Flip the image horizontally
flip_img = cv2.flip(img, 1)

# Flip the image vertically
flip_img = cv2.flip(img, 0)

# Flip the image both horizontally and vertically
flip_img = cv2.flip(img, -1)
  1. 调整图像亮度和对比度
# Increase the brightness of the image by 25
bright_img = cv2.add(img, 25)

# Decrease the brightness of the image by 25
bright_img = cv2.subtract(img, 25)

# Increase the contrast of the image by 1.5
contrast_img = cv2.multiply(img, 1.5)

# Decrease the contrast of the image by 0.5
contrast_img = cv2.multiply(img, 0.5)
  1. 模糊图像
# Blur the image with a kernel size of 5x5
blur_img = cv2.blur(img, (5, 5))

# Blur the image with a Gaussian kernel of size 5x5 and sigma value of 0
blur_img = cv2.GaussianBlur(img, (5, 5), 0)

# Blur the image with a median filter of kernel size 5x5
blur_img = cv2.medianBlur(img, 5)
结语

本文介绍了如何使用OpenCV库在Python中读取、显示和处理高度和宽度图像。我希望这会对您有所帮助,并希望您能在将来使用这些知识。