我有一個影像流,必須在 Google Colab 筆記本中顯示它,使它看起來像一個視頻,但我得到的是影像下的影像......
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)
uj5u.com熱心網友回復:
我不知道某些功能是否可以在同一個地方顯示影像。
但是我有與 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_(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)
編輯
imshow("img1", ...)使用和在兩個“視窗”中顯示影像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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479038.html
標籤:Python python-3.x opencv 谷歌合作实验室
