如何在python中创建图像并保存

时间:2019-02-12 04:21:40

标签: python-3.x opencv jupyter-notebook

我想创建图像并使用python将其存储为文件。

我希望输出的图像是黑色或白色的色块,并且图像必须具有6x6的白色或黑色色块的随机块。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码解决该问题:

#Import all libraries we will use
import random
import numpy as np
import cv2

#let's create a 6 x 6 matrix with all pixels in black color
img = np.zeros((6,6,3),np.uint8)

#let's use "for" cycle to change colorspace of pixel in a random way
for x in range(6):
    for y in range(6):
        #We use "0" for black color (do nothing) and "1" for white color (change pixel value to [255,255,255])
        value = random.randint(0,1)
        if value == 1:
            img[x,y] = [255,255,255]

#save our image as a "png" image
cv2.imwrite("6_x_6.png",img)