[PYTHON] I can't see opencv or matplotlib in vscode. There are no errors.

environment

Ubuntu20.04 Python 3.9 vscode 1.52.1 anaconda 4.8.3

Background

I ran the following opencv code on vscode, but ...

import numpy as np
import cv2
import os

image_dir = "Data/train_images/"
annotation_dir = "Data/train_annotation"

def show_image(num_str: str):
    image_path = os.path.join(image_dir, f"train_{num_str}.jpg ")
    img = cv2.imread(image_path)

    cv2.imshow('image',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    show_image("0001")

It ends normally without any error. However, the image was not displayed.

solution

You can now display it by typing the following in the vscode terminal.

$ export DISPLAY=:0

Apparently, DISPLAY was not found and it was in headless mode, so it seems that it ended normally without any error.

In the first place, in the vscode terminal, xeyes could not be displayed unless it was set to xeyes -display: 0. In addition, in a normal terminal, xeyes display was possible without taking any special measures, so there seems to be a problem with the terminal implementation of vscode.

Why did you know the solution?

First, I tried below to see if matplotlib, another drawing library, works. Then, likewise, it was not displayed without any error.

import matplotlib

import matplotlib.pyplot as plt
import numpy as np


#Data to draw as a graph
x = np.array([1,2,3,4])
y = np.array([2,3,4,5])

#Draw graph
plt.plot(x, y)
plt.show()

Next, I edited the code as follows to specify the drawing plugin.

import matplotlib
matplotlib.use('TkAgg') # <- Added

import matplotlib.pyplot as plt
import numpy as np


#Data to draw as a graph
x = np.array([1,2,3,4])
y = np.array([2,3,4,5])

#Draw graph
plt.plot(x, y)
plt.show()

Then, I got the following error.

Exception has occurred: ImportError
Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running
  File "/home/user/Programs/fish/test.py", line 6, in <module>
    import matplotlib.pyplot as plt

Isn't tk almost bundled with python in the first place? I thought, I tried the following.

import tkinter as Tk

la = Tk.Label(None, text='Hello World!', font=('Times', '18'))
la.pack()
la.mainloop()

Then the following error occurs.

Exception has occurred: TclError
couldn't connect to display ""
  File "/home/user/Programs/fish/test2.py", line 3, in <module>
    la = Tk.Label(None, text='Hello World!', font=('Times', '18'))

I had a similar error in this article before, so if I corresponded to DISPLAY =: 0 in the same way, I could solve it.

Recommended Posts

I can't see opencv or matplotlib in vscode. There are no errors.
Why can't I install matplotlib in python! !!
I get "sanity check" and "No module" errors in import numpy