LoginSignup
0
0

<エラー解決>cv2.imshow() is disabled in Colabを解消する

Posted at

エラー内容

Google colablatoryで画面上部にpurpleと表示される紫色の画像を表示させようとしたところ、
cv2.imshow()のところでエラーが出てしまったので、解決方法を備忘録として記します。

import numpy as np
import cv2

img_size = (100, 100)

img = np.array([[[150, 30, 100] for _ in range(img_size[1])] for _ in range(img_size[0])], dtype = "uint8")

cv2.imshow('purple', img)

最初に上のコードを実行してみました。
すると、

DisabledFunctionError                     Traceback (most recent call last)
<ipython-input-14-dcc119b73c38> in <cell line: 8>()
      6 img = np.array([[[150, 30, 100] for _ in range(img_size[1])] for _ in range(img_size[0])], dtype = "uint8")
      7 
----> 8 cv2.imshow('purple', img)

/usr/local/lib/python3.10/dist-packages/google/colab/_import_hooks/_cv2.py in wrapped(*args, **kwargs)
     46   def wrapped(*args, **kwargs):
     47     if not os.environ.get(env_var, False):
---> 48       raise DisabledFunctionError(message, name or func.__name__)
     49     return func(*args, **kwargs)
     50 

DisabledFunctionError: cv2.imshow() is disabled in Colab, because it causes Jupyter sessions
to crash; see https://github.com/jupyter/notebook/issues/3935.
As a substitution, consider using
  from google.colab.patches import cv2_imshow

DisabledFunctionError:
cv2.imshow() is disabled in Colab, because it causes Jupyter sessions to crash

というエラーが出てしまいました。
cv2.imshow()はJupyter sessionsをクラッシュさせてしまうため、Colabでは無効になっているということみたいです。

As a substitution, consider using from google.colab.patches import cv2_imshow
とあるように、
from google.colab.patches import cv2_imshowをインポートし、
cv2.imshow()関数の代わりにcv2_imshow()を使って再度実行してみます。

import numpy as np
from google.colab.patches import cv2_imshow

img_size = (100, 100)

img = np.array([[[150, 30, 100] for _ in range(img_size[1])] for _ in range(img_size[0])], dtype = "uint8")

cv2_imshow('purple', img)

またエラーが出てしまいました。

TypeError                                 Traceback (most recent call last)
<ipython-input-15-eb51fa524664> in <cell line: 9>()
      7 img = np.array([[[150, 30, 100] for _ in range(img_size[1])] for _ in range(img_size[0])], dtype = "uint8")
      8 
----> 9 cv2_imshow('purple', img)

TypeError: cv2_imshow() takes 1 positional argument but 2 were given

TypeError: cv2_imshow() takes 1 positional argument but 2 were given
cv2_imshow()は位置引数を1つ取るが、引数が2つ与えられているというエラーですね。
imgだけをcv2_imshow()の引数として入れてみます。

import numpy as np
from google.colab.patches import cv2_imshow

img_size = (100, 100)

img = np.array([[[150, 30, 100] for _ in range(img_size[1])] for _ in range(img_size[0])], dtype = "uint8")

cv2_imshow(img)


image.png

無事に表示されました!

まとめ

Google colablatoryで画像を表示させたいときは、
cv2.imshow()は使えないので、
代わりにcv2_imshow()を使って表示させる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0