Comment créer une image noire et une image blanche en utilisant OpenCV Python ?

WBOY
Libérer: 2023-09-06 18:57:03
avant
1216 Les gens l'ont consulté

要创建黑色图像,我们可以使用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、NumPyMatplotlib。确保您已经安装了它们。

import cv2 import matplotlib.pyplot as plt import numpy as np
Copier après la connexion

使用np.zeros()创建一个numpy.ndarray来创建黑色图像。将>sizedtype作为参数传递给这些方法。这里的数据类型是np.uint8

img = np.zeros((350, 500, 3), dtype = np.uint8)
Copier après la connexion

使用np.ones()创建一个numpy.ndarray来创建白色图像。将sizedtype作为参数传递给这些方法。这里的数据类型是np.uint8。现在我们将数组乘以255

img = np.ones((350, 500, 3), dtype = np.uint8) img = 255*img
Copier après la connexion

显示黑白图像。

cv2.imshow('black image', img)
Copier après la connexion

让我们看一下不同的示例,以便清楚地理解。

示例 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)
Copier après la connexion

输出

当你运行上面的Python程序时,它将产生以下输出窗口。

如何使用OpenCV 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)
Copier après la connexion

输出

当你运行上面的Python程序时,它将产生以下输出窗口。

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:tutorialspoint.com
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!