image looks overexposed (nearly all white) when using np.zeros with OpenCV imshow

Viewed 83

I am writing a code in openCV python for copying an image for practice purpose only, though np.copy() command is already available. Code is as below:

import numpy as np
import cv2 as cv

img = cv.imread('Photos/image_1.jpg')
r, c, d = img.shape
img_copy = np.zeros((r, c, d))
for i in range(r):
    for j in range(c):
        for k in range(d):
            img_copy[i, j, k] = img[i, j, k]

cv.imshow('original image', img)
cv.imshow('copied image', img_copy)
cv.waitKey(0)

The img_copy is not shown instead black image is shown. If I use img_copy = np.ones(rows, cols, 3), and apply same for loop, still then a white image is shown, original image is not shown. Can any one explain why this occures? Original and copied images are shown below.

enter image description hereenter image description here

1 Answers

This issue was caused by incompatible data types. To determine the data type of the image, use

img = cv.imread('Photos/image_1.jpg')
print(img.dtype)

In my testing case, the output data type was uint8

Changing

img_copy = np.zeros((r, c, d))

to

img_copy = np.zeros((r, c, d), dtype=np.uint8)

will fix this issue

Related