跳转到主内容
极星编程网:以代码为星,赴技术山海!

如何使用OpenCV Python创建一张黑色图像和一张白色图像?

要创建黑色图像,我们可以使用 np.zeros() 方法。它创建一个给定大小的 numpy n 维数组,所有元素均为 0 。由于所有元素均为零,因此当我们使用 cv2.imshow() 或 plt.imshow() 函数显示它时,它会显示黑色图像。 要创建白色图像,我们可以使用 np.ones() 方法。它创建一个给定大小的 numpy n 维数组,所有元素均为 1 。我们将此数组乘以 255 以创建白色图像。现在所有元素都是 255 ,因此当我们使用 cv2.imshow() 或 plt.imshow() 函数显示它时,它会给出白色图像. 注意 - 使用 np.zeros() 或 np.ones() 创建 numpy.ndarray 时,我们传递 dtype = np.uint8 作为参数。 步骤 您可以按照下面给出的步骤创建黑白图像 - 导入所需的库。在以下所有 Python 示例中,所需的 Python 库为 OpenCV、NumPy 和 Matplotlib 。确保您已经安装了它们。 立即学习 “ Python免费学习笔记(深入) ”;
import cv2 import matplotlib.pyplot as plt import numpy as np
使用 np.zeros() 创建一个 numpy.ndarray 来创建黑色图像。将 >size 和 dtype 作为参数传递给这些方法。这里的数据类型是 np.uint8 。
img = np.zeros((350, 500, 3), dtype = np.uint8)
使用 np.ones() 创建一个 numpy.ndarray 来创建白色图像。将 size 和 dtype 作为参数传递给这些方法。这里的数据类型是 np.uint8 。现在我们将数组乘以 255 。
img = np.ones((350, 500, 3), dtype = np.uint8) img = 255*img
显示黑白图像。
cv2.imshow('black image', img)
让我们看一下不同的示例,以便清楚地理解。 示例 1 在此示例中,我们创建一个 700x350 黑色图像。这里图像 宽度 是 700 , 高度 是 350 。
# import required libraries import cv2 import numpy as np # create a black image img = np.zeros((350, 700, 3), dtype = np.uint8) # display the image using opencv cv2.imshow('black image', img) cv2.waitKey(0)
输出 当你运行上面的Python程序时,它将产生以下输出窗口。 示例 2 在此示例中,我们创建一个 700x350 白色图像。请注意,此处图像 宽度 为 700 , 高度 为 350 。
# import required libraries import cv2 import numpy as np # create a white image img = np.ones((350, 700, 3), dtype = np.uint8) img = 255* img # display the image using opencv cv2.imshow('white image', img) cv2.waitKey(0)
输出 当你运行上面的Python程序时,它将产生以下输出窗口。

相关文章