cs231n Assignments1-numpy的使用

作者:非妃是公主
专栏:《计算机视觉》
个性签:顺境不惰,逆境不馁,以心制境,万事可成。——曾国藩
在这里插入图片描述

专栏系列文章

Cannot find reference ‘imread‘ in ‘init.py‘

error: (-209:Sizes of input arguments do not match) The operation is neither ‘array op array‘ (where

cs231n-2022-01 Assignments1-numpy的使用

ModuleNotFoundError: No module named ‘cs231n‘

numpy的使用

Numpy是Python中科学计算的核心库。它提供了一个高性能的多维数组对象,以及处理这些数组的工具。如果你已经熟悉MATLAB,你可能会发现这个教程对开始使用Numpy很有用。
运行并阅读cs231n课程网站上提供的示例代码,感觉十分简洁,对入门numpy的初学者来讲,很友好!我也没有系统学习过numpy,所以也读了一下网站上的示例代码。
网址如下:https://cs231n.github.io/python-numpy-tutorial/
有以下地方值得特别注意:
1、矩阵乘法要使用np.dot(a, b),而不是ab,ab计算的是矩阵中对应元素相乘,最后结果的维数和a,b相同。
cs231n Assignments1-numpy的使用_第1张图片
2、axis表示sum的对象到底是行,还是列,为0表示sum的行,1表示sum的是列
cs231n Assignments1-numpy的使用_第2张图片
3、numpy里面不区分行向量还是列向量,因为v和v.T相同,这也就是说,我们在进行矩阵乘法运算的时候,如果只有一个维度,我们可以不考虑到底是行向量还是列向量。
cs231n Assignments1-numpy的使用_第3张图片
4、广播机制,粗俗理解:一个矩阵m和一个数n相加,numpy很聪明,他不会报错,而是聪明的告诉这个矩阵,要给每个元素都加上n,这个过程就叫做广播。同理,我们可以用一个大矩阵加上一个小矩阵(最内层维度的大小)
cs231n Assignments1-numpy的使用_第4张图片
如果不是最内层维度,那么就会报错:
cs231n Assignments1-numpy的使用_第5张图片
它告诉我们不能广播,维度(4,3)和(4,)不匹配。
5、在运行scipy的代码时,发现报错以下错误
cs231n Assignments1-numpy的使用_第6张图片
这其实是由于版本不同导致的,由于我默认安装的为sci的最新版本,而在scipy1.0以上的版本中imread,imsave,imresize都已经被废除了,但是,由于我的python版本为3.9,这导致我无法安装scipy1.0以下的版本,所以,这里我选择了更换python的第三方库来实现同样的功能。

import imageio
import cv2 as cv
from PIL import Image
import numpy as np



# Read an JPEG image into a numpy array
img = imageio.v2.imread('assets/cat.jpg')
print(img.dtype, img.shape)  # Prints "uint8 (400, 248, 3)"

# We can tint the image by scaling each of the color channels
# by a different scalar constant. The image has shape (400, 248, 3);
# we multiply it by the array [1, 0.95, 0.9] of shape (3,);
# numpy broadcasting means that this leaves the red channel unchanged,
# and multiplies the green and blue channels by 0.95 and 0.9
# respectively.
img_tinted = img * [1, 0.95, 0.9]

# Resize the tinted image to be 300 by 300 pixels.
# img_tinted = imresize(img_tinted, (300, 300))
# np.array(Image.fromarray(img_tinted).resize((300, 300)))
img_tinted = cv.resize(img, (300, 300), interpolation=cv.INTER_AREA)  

# Write the tinted image back to disk
cv.imwrite("assets/cat_tinted.jpg", img_tinted)

在工作目录的assets文件夹中,运行结果如下:
cs231n Assignments1-numpy的使用_第7张图片
可以看到,小猫咪变胖了,而且颜色也有所变化,这主要和我们rgb三通道缩放的倍数有关(img_tinted = img * [1, 0.95, 0.9])
后面还有matplotlib,图片显示等方面的实例代码,很简单,也没有遇到问题,在此就不再一一罗列了。

你可能感兴趣的:(计算机视觉,numpy,python)