本文共 1875 字,大约阅读时间需要 6 分钟。
在OpenCV中,生成随机图像可以通过numpy库实现。以下是详细的实现步骤:
grayImage = np.random.randint(0, 255, (400, 400))cv2.imshow("GRAY", grayImage.astype(np.uint8)) bgrImage = np.random.randint(0, 255, (400, 400, 3))cv2.imshow("bgr", bgrImage.astype(np.uint8)) import numpy as npimport cv2grayImage = np.random.randint(0, 255, (400, 400))cv2.imshow("GRAY", grayImage.astype(np.uint8))bgrImage = np.random.randint(0, 255, (400, 400, 3))cv2.imshow("bgr", bgrImage.astype(np.uint8))cv2.waitKey(0)cv2.destroyAllWindows() 在OpenCV中绘制随机圆的实现步骤如下:
d = 400img = np.ones((d, d, 3), np.uint8) * 255
for i in range(0, 100): # 随机圆心坐标 center_x = np.random.randint(0, high=d) center_y = np.random.randint(0, high=d) # 随机半径 radius = np.random.randint(5, high=d//5) # 随机颜色 color = np.random.randint(0, high=256, size=(3,)).tolist() # 绘制圆 cv2.circle(img, (center_x, center_y), radius, color, -1)
cv2.imshow("img", img)cv2.waitKey()cv2.destroyAllWindows() import numpy as npimport cv2def main(): d = 400 img = np.ones((d, d, 3), np.uint8) * 255 # 创建白色背景 for _ in range(100): # 绘制100个圆 # 随机圆心坐标 center_x = np.random.randint(0, d) center_y = np.random.randint(0, d) # 随机半径 radius = np.random.randint(5, d//5) # 随机颜色 color = np.random.randint(0, 256, size=(3,)).tolist() # 绘制圆 cv2.circle(img, (center_x, center_y), radius, color, -1) cv2.imshow("img", img) cv2.waitKey() cv2.destroyAllWindows()if __name__ == '__main__': main() 以上代码可直接复制运行,适合开发和测试用途。
转载地址:http://enhfk.baihongyu.com/