Reputation: 31
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.
Upvotes: 2
Views: 602
Reputation: 15387
OpenCV's imshow()
is sensitive to the element type of the array you pass it.
When the element type is np.uint8
, the values must be in the range of 0
to 255
.
When the element type is np.float32
or np.float64
, the values must be in the range of 0.0
to 1.0
.
You have two options:
Either scale your values: img_copy / 255
Or clip and convert your values: np.clip(img_copy, 0, 255).astype(np.uint8)
Upvotes: 0
Reputation: 21
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
Upvotes: 2