4
import numpy as np
import cv2

# first_method
# img = cv2.imread('sample.jpg')
# second_method
# img = np.zeros((1000, 1000, 3), np.int8) 

while True:
    cv2.imshow('sample', img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()

In the above code I'm trying to display the image using imshow() function of opencv. When I try to use the first method, i.e crating an array from a sample image the code work perfectly, but when I create my own array I get the following error-

PS C:\Users\tanma\Dropbox\Coding\python\AI> python .\test_1.py
Traceback (most recent call last):
  File ".\test_1.py", line 16, in <module>
    cv2.imshow('sample', img)
cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\highgui\src\window_w32.cpp:1230: error: (-215:Assertion failed) dst.data == (uchar*)dst_ptr in function 'cvShowImage'
Tanmay Gupta
  • 41
  • 1
  • 2
  • your code is working correctly with the second method under opencv2 version 3.4.3 – madik_atma Jan 25 '19 at 18:25
  • You are showing the same image, over and over again, every 20ms. I'm not surprised you crash stuff eventually. Try moving the `imshow` out of the loop. – Cris Luengo Jan 25 '19 at 18:26
  • 1
    @CrisLuengo Sure it's a lot of useless work calling `imshow` with the same image, but it's just updating the internal copy of the image in the same window -- why should it cause a crash (unless there's some bug in OpenCV itself)? – Dan Mašek Jan 25 '19 at 19:13
  • 2
    There is probably a typo: `np.uint8` instead of `np.int8`? – Berriel Jan 26 '19 at 00:30
  • It's working guys, thanks so much. I uninstalled and reinstalled opencv. – Tanmay Gupta Jan 26 '19 at 06:49
  • Related: https://stackoverflow.com/q/53267856/6358973 – calocedrus Mar 19 '19 at 08:44

2 Answers2

5

I had a similar problem using OpenCV 4.0.0. According to this, the bug is fixed in 4.0.1, so you can just update the opencv-python package.

My image was of type floating-point, but according to OpenCV Documentation it is ok to show such images:

  • If the image is 8-bit unsigned, it is displayed as is.
  • If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
  • If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].
Butterfly
  • 435
  • 6
  • 15
  • The choice of floating point vs int will limit the range of values allowed which is a bit weird... But this answer points me to the right direction! – yuqli Dec 10 '19 at 23:59
2

Your own array generates an error because the data type 'int8' is incorrect and needs to be changed to 'uint8', i.e. an 8-bit unsigned integer. This is because colors are represented by integers 0 - 255, and using a signed integer would only allow for positive integers up until 127.