python plt.plot(...)不显示窗口,我错过了什么[副本]

atmip9wb  于 2023-06-20  发布在  Python
关注(0)|答案(1)|浏览(127)

此问题已在此处有答案

No plot window in matplotlib(12个回答)
昨天关门了。
我在VScode上练习开放简历。
我习惯于使用以下结构来显示图像:

import cv2
import numpy as np
import matplotlib.pyplot as plt

puppy = cv2.imread('./DATA/00-puppy.jpg')
horse = cv2.imread('./DATA/horse.jpg')
rainbow = cv2.imread('./DATA/rainbow.jpg')

# "inplace" operations on these images such as
# puppy = cv2.cvtColor(puppy, cv2.COLOR_BGR2RGB)
# etc...

img_to_show_1 = puppy
img_to_show_2 = horse
img_to_show_3 = rainbow

# ---> beginning of the "while True ... - if 0xFF == 27: break" structure

cv2.namedWindow(winname='window_1')
cv2.namedWindow(winname='window_2')
cv2.namedWindow(winname='window_3')

while True:
    cv2.imshow('window_1', img_to_show_1)
    cv2.imshow('window_2', img_to_show_2)    
    cv2.imshow('window_3', img_to_show_3)

    if cv2.waitKey(1) & 0xFF == 27: # stop loop when 'esc' key is pressed
        break

cv2.destroyAllWindows()

# ---> end of the "while True ... - if 0xFF == 27: break" structure

现在,我已经计算了存储在puppy变量中的图像值的直方图

hist_values = cv2.calcHist([puppy], channels=[0], mask=None, histSize=[256], ranges=[0,256])

在jupyter笔记本上,这可以通过简单的操作来显示:

plt.plot(hist_values)

但在VScode上,这并没有显示任何东西。
有没有一种方法可以在VScode上显示这个图像,而不需要添加任何其他的图形扩展?
有没有一种方法可以利用同样的“当真…- 如果0xFF == 27:打破”结构,为了有这个图像也消失与其他人,因为我按下'esc'键?

gr8qqesn

gr8qqesn1#

我找到了一个解决办法。
这是基于使用opencv module方法保存图像并使用matplotlib方法重新加载图像:

import cv2
import numpy as np
import matplotlib.pyplot as plt

puppy = cv2.imread('./DATA/00-puppy.jpg')
horse = cv2.imread('./DATA/horse.jpg')
rainbow = cv2.imread('./DATA/rainbow.jpg')

# "inplace" operations on these images such as
# puppy = cv2.cvtColor(puppy, cv2.COLOR_BGR2RGB)
# etc...

hist_values = cv2.calcHist([puppy], channels=[0], mask=None, histSize=[256], ranges=[0,256])

plt.plot(hist_values)
plt.plot([1, 2])
mypath = 'my/path/hist_values.jpg'
plt.savefig(mypath)

hist_values_img = cv2.imread(mypath)

import os
try: 
    os.remove(hist_values_path)
except: 
    print("could not remove {}".format(hist_values_path))

img_to_show_1 = puppy
img_to_show_2 = hist_values_img
img_to_show_3 = rainbow

# ---> beginning of the "while True ... - if 0xFF == 27: break" structure

cv2.namedWindow(winname='window_1')
cv2.namedWindow(winname='window_2')
cv2.namedWindow(winname='window_3')

while True:
    cv2.imshow('window_1', img_to_show_1)
    cv2.imshow('window_2', img_to_show_2)    
    cv2.imshow('window_3', img_to_show_3)
    plt.show()

    if cv2.waitKey(1) & 0xFF == 27: # se premo esc
        break

cv2.destroyAllWindows()

# ---> end of the "while True ... - if 0xFF == 27: break" structure

这样我就不会混合GUI了,当我按下“Esc”时,直方图图像会和其他图像一起闭合。
作者:@ChristophRackwitz

相关问题