colab中的一些特殊设置

与本地部署不同,colab中一些库的使用有些区别,在本文中记录。

预装库

深度学习需要的大部分库已预先在colab中安装,包括numpy,pandas,matplotlib,sklearn,pytorch,TensorFlow,xgboost,lightgbm,opencv,pillow等。使用时直接import即可。

加载谷歌云盘

在colab中,程序和数据集尽量装在谷歌云盘上,便于查看和保存。但每次使用需把云盘加载到colab中。/content/drive/MyDrive/是云盘的路径,后续路径根据工作需要自行设置。

from google.colab import drive
import os
drive.mount('/content/drive')
os.chdir("/content/drive/MyDrive/Colab_Notebooks/图像分类/")#工作路径

matplotlib的中文设置

matplotlib不能自动输出中文,需要修改字体,往往使用SimHei字体。colab中该字体需自行下载。先下载字体配置文件

!wget https://zihao-openmmlab.obs.cn-east-3.myhuaweicloud.com/20220716-mmclassification/dataset/SimHei.ttf --no-check-certificate

这是下载到当前文件夹,下好可以剪切到自己想要的位置。然后将这个字体加入字体库

import matplotlib
font_path="/content/drive/MyDrive/Colab_Notebooks/SimHei.ttf"#字体库路径
matplotlib.font_manager.fontManager.addfont(font_path)#添加字体

然后就和本地的加载方法一样了

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['font.family']='SimHei' # 设置字体
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

opencv

opencv的使用与本地环境有两个主要区别:图片输出,摄像头调用。
图片输出不得使用cv2.imshow()而是用google的cv2_imshow代替

from google.colab.patches import cv2_imshow
import cv2
img=cv2.imread('/content/drive/MyDrive/Colab_Notebooks/图像分类/test_img/husky1.jpeg')   
cv2_imshow(img)

由于是网页上打开,colab不能使用本地的摄像头,只能用网页摄像头。在左侧菜单栏找到代码段选项,点开选择Camera Capture,把两段代码粘下来就能用了。

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

def take_photo(filename='photo.jpg', 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();

      // Resize the output to fit the video element.
      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);

      // Wait for Capture to be clicked.
      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])
  with open(filename, 'wb') as f:
    f.write(binary)
  return filename
from IPython.display import Image
try:
filename = take_photo()
print('Saved to {}'.format(filename))

# Show the image which was just taken.
display(Image(filename))
except Exception as err:
# Errors will be thrown if the user does not have a webcam or if they do not
# grant the page permission to access it.
print(str(err))

你可能感兴趣的:(python,深度学习,云计算)