T
T
Touchme2020-10-25 15:39:24
Python
Touchme, 2020-10-25 15:39:24

How to rewrite OpenCV python image?

Understanding image processing in python with OpenCV. There was a following problem: If I simply shift an array of the image in a new array, the image is strongly highlighted. As if I write there only white pixels. Here is the code:

import cv2 as cv
import numpy as np

img = cv.imread("test1.png")
print(img.shape)
line, row = img.shape[:2]
new_img = np.zeros([line, row, 3])
i = 0
while i < line:
    j = 0
    while j < row:
        new_img[i, j, 0] = img[i, j, 0]
        new_img[i, j, 1] = img[i, j, 1]
        new_img[i, j, 2] = img[i, j, 2]
        j += 1
    i += 1

cv.imshow("Image", new_img)
cv.waitKey(0)
cv.destroyAllWindows()

as an input image, I give just a gray rectangle of size 19x21. But when I output new_img, I get a white rectangle.
Judging by the debugger, the array is rewritten correctly. (I apologize in advance if I called something by wrong names, in the world of python recently)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Touchme, 2020-10-25
@Touchme

Understood. When an array is created, the array np.zeros([line, row, 3])cell is created with the type numpy.float64. But image pixels are in 8-bit unsigned integer format, i.e. numpy.uint8.
You need to make a type cast:
new_img = new_img.astype(np.uint8)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question