0

I have a code:

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()

that generates grid like this one:

enter image description here

So cv2.imshow shows the grid but cv2.imwrite writes only initial black background not the grid for some reason. How to fix that?

3
  • I have a strange suspicion, could you move cv2.waitKey(0) one line up? so between the imshow and imwrite? and also make sure that the file you check is really the file you saved (check if the timestamp on the file is changed) Commented Mar 6, 2022 at 9:00
  • @Nullman it's change nothing Commented Mar 6, 2022 at 9:20
  • Does this answer your question? why my imshow differs from imwrite Commented Mar 6, 2022 at 12:57

1 Answer 1

4

You need to scale the color channels:

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

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

Alternatively you can create a "white" image with type uint8:

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

img = numpy.ones((255, 465, 3), dtype = numpy.uint8) * 255
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.