Pillow1、OpenCV2
PIL库最常用的类3:Image、ImageFilter、ImageEnhance
im = Image.open('1.jpg')
r,b,g=im.split()
r.show()
im1 = Image.merge("RGB",(r,r,g))
im1.show()
im_arr = np.asarray(im)
im_dat = list(im.getdata())
# im.size:177(width)x140(height),
# im_arr.shape:(140, 177, 3),即(H,W,C)。len(im_arr):140,即140行;len(a[0]:177,即每行177列;len(a[0][0]):3,即每行每列的位置是每一个像素(R,G,B)三元组的值。
# len(im_dat):24780,即177x140
# im_arr[0][0],im_dat [0],im.getpixel((0,0))分别为(array([111, 60, 47], dtype=uint8), (111, 60, 47), (111, 60, 47))
# 构造出类似im_arr的array数组来生成图片:Image.fromarray(),即 np.asarray(im)的逆操作。
for i, value in enumerate(im.histogram()):
print(i, value) # im为RGB三通道图片,则len为256*3=768
# r,g,b=im.split()
# im.histogram()[19] == r.histogram()[19]
# im.histogram()[19+256] == g.histogram()[19]
# im.histogram()[19+256+256] == b.histogram()[19]
im_gif = Image.open("a.gif")
im_gif.show() #当文件序列被打开时,PIL库自动指定到第0帧上
im_gif.seek(3) #在给定的文件序列中查找指定的帧
im_gif.show()
print(im_gif.tell()) #返回当前帧所处位置,从0开始计算,此处返回3
选择预定义滤波器:ImageFilter.BLUR/CONTOUR/DETAIL/EDGE_ENHANCE/EDGE_ENHANCE_MORE/EMBOSS/FIND_EDGES/SMOOTH/SMOOTH_MORESHARPEN,进行滤波:filter()
from PIL import ImageFilter
blu = im.filter(ImageFilter.BLUR) ##均值滤波
con = im.filter(ImageFilter.CONTOUR) ##找轮廓
edge = im.filter(ImageFilter.FIND_EDGES) ##边缘检测
先选择待增强的属性:ImageEnchance.Color/Contrast/Brightness/Sharpness,再将属性的数值增强factor倍:enchance(factor)
from PIL import ImageEnchance
col_enchan = ImageEnhance.Color(im).enhance(10) ##颜色增强10倍
col_enchan = ImageEnhance.Brightness(im).enhance(10) ##亮度增强10倍
与PIL库的区别
import cv2
im=cv2.imread(r"0.jpg") # (140, 177, 3)
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.imshow('img',im)
cv2.waitKey(2000) # 2s后自动销毁
cv2.destroyAllWindows()
cv2.imwrite(r"1.png",im)
# 类似from PIL import Image,import numpy as np
im_pil = Image.open(r"0.jpg")
im_arr = np.asarray(im_pil ) # (140, 177, 3)
# cv2库得到的im和PIL库得到的im_arr都是ndarray数据,(140, 177, 3),即(H,W,C)。
# 但在C通道的三元组中,im_arr是(R,G,B),而im是(B,G,R)
# 显示图片时,分别是cv2.imshow(im)和im_pil .show()
# 采用plt库时:import matplotlib.pyplot as plt
plt.imshow(im_arr) #按(H,W,C)且C为(R,G,B)显示
# 但不能plt.imshow(im),不然就将原图RGB通道显示成了BGR通道图片,可以用plt.imshow(im[:,:,::-1])
# im与im_pil的转换,如将:cv2的im(B,G,R)转成pil-np的im_arr(R,G,B)
r, g, b = cv2.split(im)
img_pil = cv2.merge([b,g,r]), plt.imshow(img_pil)
HSV模型4,
通过HSV空间对色调(Hue),饱和度(Saturation),明度(Value)进行调节5。
im_hsv = cv2.cvtColor(im,cv2.COLOR_BGR2HSV)
im_h[:,:,0] = im_hsv[:,:,0]+15 # 改变色调值会让图像整体改变颜色
im_s[:,:,1] = 0.5*colorless_hsv[:,:,1] # 减小饱和度会让图像损失鲜艳
im_v[:,:,2] = 0.5*darker_hsv[:,:,2] # 减小亮度会让图像变暗
im_bgr = cv2.cvtColor(im_h或im_s或im_v,cv2.COLOR_HSV2BGR)
详细区别:
https://pillow.readthedocs.io/en/stable/handbook ↩︎
https://docs.opencv.org/4.6.0/index.html ↩︎
https://blog.csdn.net/weixin_45627039/article/details/124114475 ↩︎
https://blog.csdn.net/qq_38179373/article/details/109168414 ↩︎
https://blog.csdn.net/jiaoyangwm/article/details/79961778 ↩︎