python PIL和CV对 图片的读取,显示,裁剪,拉伸,保存
PIL 图片操作
读取图片
img = Image.open("a.jpg")
显示图片
im.show() # im是Image对象,im是numpy类型,通过Image.fromarray(nparr, mode='RGB')函数转换为Image对象
图片的size
(width, height) = img.size
图片的模式
mode = img.mode
裁剪
img_c = img.crop(x1,y1,x2,y2)
拉伸图片
img = img.resize((size,size), Image.ANTIALIAS)
保存图片
img.save(path)
ImageDraw
imDrwa = ImageDraw.Draw(img)
# boxes = [[10, 20, 129, 255],[126, 0, 221, 164]]
imDrwa.rectangle((x1, y1, x2, y2), outline="red") # 画矩形
r = 2
x1 = 100
y1 = 100
imDrwa.ellipse((x1-r, y1-r, x1+r, y1+r), fill=(255,0,255)) # 画椭圆,r固定为圆
img.show()
图片过大加载,opencv加载30M+报错
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
img = Image.open(path).convert("RGB")
img = np.array(img)
img = img[:,:,::-1]
OpenCV
读取图片
im = cv2.imread()
显示图片
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
拉伸
img=cv2.resize(image,(size,size),interpolation = cv2.INTER_AREA)
保存图片
cv2.imwrite('1.jpg',img, [int( cv2.IMWRITE_JPEG_QUALITY), 95]) # 默认95
opencv压缩图片
import cv2 as cv
def resize_image(src_path, rate, save_path):
img = cv.imread(src_path)
h,w,c = img.shape
resize_img = cv.resize(img, (int(w * rate), int(h * rate)), interpolation=cv.INTER_AREA)
cv.imwrite(save_path, resize_img, [int(cv.IMWRITE_JPEG_QUALITY), 95])
src_path = r"C:\Users\RoseC\Desktop\219.jpg" # 原图片
rate = 0.5 # 压缩的比例
save_path = r"C:\Users\RoseC\Desktop\example.jpg" # 保存图片
resize_image(src_path, rate, save_path)