Colab中使用cv2_imshow加载图片:无需文件路径的方法咨询
在Colab中无需手动设置文件路径使用cv2_imshow加载图片的方法
针对你在手写体模型测试流程中遇到的需求,这里提供几种不用手动写文件路径就能用cv2_imshow加载图片的实现方式:
1. 直接上传本地图片到会话内存
不用把图片存到Colab的文件系统,直接上传后从内存读取,完全不需要路径:
import cv2 as cv import numpy as np from google.colab.patches import cv2_imshow from google.colab import files from tensorflow.keras.models import load_model # 触发本地文件上传窗口 uploaded = files.upload() # 自动获取上传的第一个图片文件 img_name = next(iter(uploaded.keys())) # 从内存解码图片数据,跳过文件路径步骤 img_color = cv.imdecode(np.frombuffer(uploaded[img_name], np.uint8), cv.IMREAD_COLOR) # 原有的图片处理流程 img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY) ret, img_binary = cv.threshold(img_gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU) kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5)) img_binary = cv.morphologyEx(img_binary, cv.MORPH_CLOSE, kernel) cv2_imshow(img_binary) cv.waitKey(0)
运行代码后会弹出本地文件选择窗口,选中要测试的手写体图片即可,自动处理后续步骤。
2. 调用摄像头实时捕获手写体图片
如果要直接拍摄手写体测试,不用提前准备图片文件,直接调用设备摄像头:
import cv2 as cv import numpy as np from google.colab.patches import cv2_imshow from IPython.display import display, Javascript from google.colab.output import eval_js from base64 import b64decode def take_photo(quality=0.8): js = Javascript(''' async function takePhoto(quality) { const div = document.createElement('div'); const capture = document.createElement('button'); capture.textContent = 'Capture'; div.appendChild(capture); const video = document.createElement('video'); video.style.display = 'block'; const stream = await navigator.mediaDevices.getUserMedia({video: true}); document.body.appendChild(div); div.appendChild(video); video.srcObject = stream; await video.play(); await new Promise((resolve) => capture.onclick = resolve); const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); stream.getVideoTracks()[0].stop(); div.remove(); return canvas.toDataURL('image/jpeg', quality); } ''') display(js) data = eval_js('takePhoto({})'.format(quality)) binary = b64decode(data.split(',')[1]) # 临时保存到Colab会话(不用手动设置路径) with open('temp_photo.jpg', 'wb') as f: f.write(binary) return 'temp_photo.jpg' # 捕获摄像头图片 img_path = take_photo() # 读取捕获的图片 img_color = cv.imread(img_path, cv.IMREAD_COLOR) # 原有的图片处理流程 img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY) ret, img_binary = cv.threshold(img_gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU) kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5)) img_binary = cv.morphologyEx(img_binary, cv.MORPH_CLOSE, kernel) cv2_imshow(img_binary) cv.waitKey(0)
运行后会请求摄像头权限,点击“Capture”按钮即可拍摄图片,自动进入后续处理,全程不用手动指定路径。
3. 从Google Drive自动读取图片
如果你的手写体图片存在Google Drive里,挂载Drive后可以自动遍历文件夹获取图片,不用手动输入单个文件路径:
import cv2 as cv import numpy as np from google.colab.patches import cv2_imshow from google.colab import drive import os # 挂载Google Drive(按照提示完成授权) drive.mount('/content/drive') # 替换成你Drive里存放图片的文件夹路径,自动筛选图片文件 drive_img_dir = '/content/drive/MyDrive/手写体测试图片' img_files = [f for f in os.listdir(drive_img_dir) if f.lower().endswith(('.jpg', '.png', '.jpeg'))] # 取第一个图片文件(批量测试可以循环遍历img_files) img_color = cv.imread(os.path.join(drive_img_dir, img_files[0]), cv.IMREAD_COLOR) # 原有的图片处理流程 img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY) ret, img_binary = cv.threshold(img_gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU) kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5)) img_binary = cv.morphologyEx(img_binary, cv.MORPH_CLOSE, kernel) cv2_imshow(img_binary) cv.waitKey(0)
只需要修改drive_img_dir为你Drive里的文件夹路径,代码会自动筛选出图片文件,不用手动写具体的图片文件名和路径。
内容的提问来源于stack exchange,提问作者이주현
相关产品推荐
相关产品推荐

