Ryoh
Ryoh

Reputation: 37

Image copy does not show the same image on OpenCV

I would like to display a copy of an image but it does not work.

def display_and_close(img):
    cv2.imshow("test",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

img = cv2.imread('assets/tests.jpeg',0)
width, height = img.shape
new_img = np.zeros((width, height))
new_img[:width, :height] += img[:width, :height]


display_and_close(new_img)
display_and_close(img)

I also tried to iterate over the image like this :

for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        new_img[i][j] = img[i][j]

but it does not work again

Upvotes: 0

Views: 204

Answers (1)

fmw42
fmw42

Reputation: 53081

You need to specify the dtype as uint8 for your black image in Python/OpenCV or it will default to float.

So replace

new_img = np.zeros((width, height))

with

new_img = np.zeros((width, height), dtype=np.uint8)

Also note that Numpy and shape use y,x notation (height, width) and you are using (width, height). But since you get the shape reversed also, you are OK. But you should reverse both.

Upvotes: 1

Related Questions