图像读取
经各种尝试后个人比较喜欢用cv2包来读取图片,另有很多优秀的方法不赘述,如使用imageio包等,还请各位看官自行查阅~
CV2
引入包
import cv2
读取图片
def read_image(path):
image = cv2.imread(path) # bgr
image = image[:, :, ::-1] # rgb
return image
**!注意!**使用CV2包得到的不是通常的RGB顺序,而是BGR顺序,在上述代码第3行中可将图片颜色空间由BGR转为RGB
显示图片
引入包
import matplotlib.pyplot as plt
显示
def show_image(image):
plt.imshow(image)
plt.show()
方法写好了,自己调用一下就可以啦~
RFB颜色空间转为ycbcr颜色空间
这里是用的网上的资源,网址贴上
RGB与YCBCR颜色空间转换及python实现
写得真的很好!要好好看!(虽然我不能完全看懂)
然后代码抄下来就是这个样子,太牛逼了
def rgb2ycbcr(image): # 将rgb图像转换为YCbCr图像
if len(rgb_image.shape) != 3 or rgb_image.shape[2] != 3:
raise ValueError("input image is not a rgb image")
image = rgb_image.astype(np.float32)
# 创建变换矩阵和偏移量
transform_matrix = np.array([[0.257, 0.504, 0.098],
[-0.148, -0.291, 0.439],
[0.439, -0.368, -0.071]])
shift_matrix = np.array([16, 128, 128])
ycbcr_image = np.zeros(shape=rgb_image.shape)
w, h, _ = rgb_image.shape
# 遍历每个像素点的三个通道进行变换
for i in range(w):
for j in range(h):
ycbcr_image[i, j, :] = np.dot(transform_matrix, rgb_image[i, j, :]) + shift_matrix
return ycbcr_image
写到后来发现有现成的包
ycbcr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2YUV)
一句话可以搞定,想哭