使用 OpenCV 在 Google Colab 中显示流图像

Display a stream images in Google Colab using OpenCV

我有图像流,必须在 Google Colab notebook 中显示它,使其看起来像视频,但我得到的是图像下方的图像 ...

from google.colab import drive
drive.mount('/content/drive')

# importing cv2
import cv2
import imutils
from google.colab.patches import cv2_imshow
from IPython.display import clear_output
import os

folder = r'/content/drive/images/'

for filename in os.listdir(folder) :
    VALID_FORMAT = (".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG")
    if filename.upper().endswith(VALID_FORMAT):
        path = folder + filename
        image = cv2.imread(path)
        # resize image
        frame = imutils.resize(image, width=1200)
        # show the image
        cv2_imshow(frame) 
        cv2.waitKey(20)

不知道有没有功能可以在同一个地方显示图片

但我有代码,我将它与 cv2 一起使用,以将来自网络摄像头的帧显示为视频。

这里是缩小版。

imshow(name, image) 创建 <img id="name"> 并将 src/url 替换为转换为字符串的图像 base64 并且浏览器将其显示为图像。

imshow() 使用 name 检查是否已经存在 <img id="name"> 并替换之前的图像。

from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64encode
import cv2

def imshow(name, img):
  """Put frame as <img src="data:image/jpg;base64,...."> """

  js = Javascript('''
  async function showImage(name, image, width, height) {
    img = document.getElementById(name);
    if(img == null) {
      img = document.createElement('img');
      img.id = name;
      document.body.appendChild(img);
    }
    img.src = image;
    img.width = width;
    img.height = height;
  }
  ''')

  height, width = img.shape[:2]

  ret, data = cv2.imencode('.jpg', img)   # compress array of pixels to JPG data
  data = b64encode(data)                  # encode base64
  data = data.decode()                    # convert bytes to string
  data = 'data:image/jpg;base64,' + data  # join header ("data:image/jpg;base64,") and base64 data (JPG)

  display(js)
  eval_js(f'showImage("{name}", "{data}", {width}, {height})')  # run JavaScript code to put image (JPG as string base64) in <img>
                                          # `name` and `data` in needs `" "` to send it as text, not as name of variabe.

这里是使用它来显示来自维基百科的图像 Lenna 的代码。

import requests
import cv2
import numpy as np
import time

url = 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png'

data = requests.get(url)

frame1 = cv2.imdecode(np.frombuffer( data.content, np.uint8), 1)
frame2 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)

for _ in range(3):
  imshow("temp", frame1)
  time.sleep(1)
  imshow("temp", frame2)
  time.sleep(1)

编辑

使用 imshow("img1", ...)imshow("img2", ...)

在两个“windows”中显示图像
import os
import cv2
import imutils
import time

folder = r'/content/drive/images/'

VALID_FORMAT = (".JPG", ".JPEG", ".PNG")

for number, filename in enumerate(os.listdir(folder)):
    if filename.upper().endswith(VALID_FORMAT):
        path = os.path.join(folder, filename)

        image = cv2.imread(path)
        
        frame = imutils.resize(image, width=400)

        number = number % 2        
        imshow(f"img{number}", frame)

        time.sleep(1)