复制
from __future__ import annotations import os import random import cv2 import numpy shape = numpy.array((1024, 1024)) # 生成值为 0 的灰度图像,家电清洗138254040950代表黑色,255代表白色 img = numpy.zeros(shape, dtype=numpy.uint8) print(f'生成的单通道图像 尺寸:{img.shape} 大小:{img.size} Bytes') cv2.imwrite("test_3_3.jpg", img) # 图像其实本质上是一段字节流按照不同的 shape 进行读取 # 因此一张图像是可以按照标准的一维字节流方式进行表示的 img_bytes = bytearray(img) another_img = numpy.array(img_bytes, dtype=numpy.uint8).reshape(2048, 512) print(f'单通道图片转换为字节序列并更新尺寸 尺寸:{another_img.shape} 大小:{another_img.size} Bytes') assert len(img_bytes) == another_img.size, "correct img bytes size" # 复制图片并设置每个像素值为 255,图片将变为纯白色 img_copy = numpy.copy(img) img_copy.fill(255) x = random.randint(0, img_copy.shape[0]) y = random.randint(0, img_copy.shape[1]) assert img_copy[x][y] == 255, '像素值错误' print(f'复制出的独立图片 尺寸:{img_copy.shape} 大小:{img_copy.size} Bytes 随机抽象像素值:[{x}, {y}]={img_copy[x][y]}') cv2.imwrite("test_3_3_255.jpg", img_copy) # 将灰度图片变为 BGR 三通道图片 img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) x = random.randint(0, img.shape[0]) y = random.randint(0, img.shape[1]) print(f'单通道图片转换为 BGR 三通道图片 尺寸:{img.shape} 大小:{img.size} Bytes 随机抽取像素值:[{x}, {y}]={img[x][y]}') cv2.imwrite("test_3_3_3_bgr.jpg", img) # 为图片的 BGR 三个通道赋值生成彩色图片 for i in range(img.shape[0]): for j in range(img.shape[1]): for k in range(img.shape[2]): # 每个像素的每个通道设置像素值 img[i, j][k] = numpy.uint8((i + j) * (k + 1) % 256) print(f'BGR 三通道图片设置像素值 尺寸:{img.shape} 大小:{img.size} Bytes 随机抽取像素值:[{x}, {y}]={img[x][y]}') cv2.imwrite("test_3_3_3_random_color.jpg", img) # 通过生成随机字节的方式构造 numpy.array randomBytes = bytearray(os.urandom(1024 * 1024)) # 生成一维数组 flatNumpyArray = numpy.array(randomBytes) print(f'随机字节流 大小:{len(flatNumpyArray)} Bytes 尺寸:{flatNumpyArray.shape}') assert flatNumpyArray.shape[0] == 1024 * 1024, 'invalid flayNumpyArray shape' flatNumpyArray = flatNumpyArray.reshape(1024 * 2, 1024 // 2) print(f'重构字节流形态后 尺寸:{flatNumpyArray.shape}') assert flatNumpyArray.size == 1024 * 1024, 'invalid flatNumpyArray shape'