图片操作
Scipy提供了很多基础的函数去处理图片。例如,它有从硬盘读到numpy数组的函数,也有将numpy数组写到硬盘的函数,并且可以重新设置大小。这里有一个简单的例子来展示这些函数:
from scipy.misc import imread, imsave, imresize
# Read an JPEG image into a numpy array
img = 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))
# Write the tinted image back to disk
imsave('assets/cat_tinted.jpg', img_tinted)
左边是原图。右边是染色和重新定义大小的图
Matlab文件
这些功能scipy.io.loadmat和scipy.io.savemat允许你读取和写matlab文件,具体参考此文档
两点之间的距离
SciPy定义了许多有用的函数来计算点之间的距离。
比如函数 scipy.spatial.distance.pdist就计算集合中所有点之间的距离:
import numpy as np
from scipy.spatial.distance import pdist, squareform
# Create the following array where each row is a point in 2D space:
# [[0 1]
# [1 0]
# [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
# Compute the Euclidean distance between all rows of x.
# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
# and d is the following array:
# [[ 0. 1.41421356 2.23606798]
# [ 1.41421356 0. 1. ]
# [ 2.23606798 1. 0. ]]
d = squareform(pdist(x, 'euclidean'))
print(d)
你可以看到更详细的文档
还有一个相似的scipy.spatial.distance.cdist函数也是可以计算的,具体文档