Home > Net >  Display a stream images in Google Colab using OpenCV
Display a stream images in Google Colab using OpenCV

Time:05-21

I have a stream of images and have to display it in Google Colab notebook such that it looks like a video, But what I get is a image under image ...

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)

CodePudding user response:

I don't know if some function can display image in the same place.

But I have code which I used with cv2 to display frames from webcam as video.

Here reduced version.

imshow(name, image) creates <img id="name"> and replaces src/url with image converted to string base64 and browser shows it as image.

imshow() uses name to check if already exist <img id="name"> and it replaces previous image.

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.

And here code which uses it to display image Lenna from Wikipedia.

import requests
import cv2
import numpy as np
import time

url = 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_(test_image).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)

EDIT

Display images in two "windows" using imshow("img1", ...) and imshow("img2", ...)

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)
  • Related