cv2.imwrite 不保存结果图像,仅保存初始图像

cv2.imwrite doesn't save result image but initial only

我有一个代码:

import cv2
import numpy

background = numpy.zeros((1080, 1920, 3))
img = numpy.ones((255, 465, 3))
offset = numpy.array((12, 12))

x_offset = offset[0]
y_offset = offset[1]

img_w = img.shape[1]
img_h = img.shape[0]

background_w = background.shape[1]
background_h = background.shape[0]

x = x_offset
y = y_offset
for i in range(0, 16):
    background[y:y + img.shape[0], x:x + img.shape[1]] = img
    x += img_w + x_offset
    if x > background_w - img_w:
        x = x_offset
        y += img_h + y_offset

cv2.imshow("test", background)
cv2.imwrite("background.jpg", background)
cv2.waitKey(0)
cv2.destroyAllWindows()

生成这样的网格:

所以 cv2.imshow 显示了网格,但 cv2.imwrite 出于某种原因只写了初始黑色背景而不是网格。如何解决?

您需要缩放颜色通道:

cv2.imwrite("background.jpg", background)

cv2.imwrite("background.jpg", background * 255)

或者,您可以创建类型为 uint8:

的“白色”图像

img = numpy.ones((255, 465, 3))

img = numpy.ones((255, 465, 3), dtype = numpy.uint8) * 255