python 生成白画布,黑画布和指定颜色画布,纯白色图片或黑色图片或纯色图片

python 生成白色画布方法:

参考资料: https://stackoverflow.com/questions/10465747/how-to-create-a-white-image-in-python

方法一:

In [7]: import numpy as np

In [8]: width = 100

In [9]: height = 200

In [10]: image = np.zeros([height, width, 3], dtype=np.uint8)

In [11]: unique, counts = np.unique(image, return_counts=True)

In [12]: unique
Out[12]: array([0], dtype=uint8)

In [13]: image.fill(255)

In [14]: np.unique(image)
Out[14]: array([255], dtype=uint8) 

方法二:

In [1]: import numpy as np                                                                                                                                              

In [2]: width = 100                                                                                                                                                     

In [3]: height = 200                                                                                                                                                    

In [4]: image = 255 * np.ones((height, width, 3), dtype=np.uint8)                                                                                                       

In [5]: image.shape                                                                                                                                                     
Out[5]: (200, 100, 3)

In [6]: np.unique(image)                                                                                                                                                
Out[6]: array([255], dtype=uint8)

生成黑色画布:

In [8]: image = np.zeros((height, width, 3), dtype=np.uint8)                                                                                                            

In [9]: np.unique(image)                                                                                                                                                
Out[9]: array([0], dtype=uint8)

生成有颜色的纯色画布:

In [10]: image = [75, 19, 77] * np.ones((640, 480, 3), np.uint8)                                                                                                        

In [11]: np.unique(image)                                                                                                                                               
Out[11]: array([19, 75, 77])

注意: np.unique是得到数组中存在的不重复的元素,具体用法可以看 https://www.cnblogs.com/ttweixiao-IT-program/p/13895384.html

以上的方法只要你理解了,图片的本质就是一个二维数组或者三维的数组,当数组的类型为uint8时,最大的255就是白色,最小的0就是黑色,然后在设置好图形形状之后,你就可以根据填充你想要的像素值得到相应的纯色图片啦~