Live2D

Python - PIL&cv2相互转换

简介

PIL和cv2是Python中两个常用的图像处理库,PIL一般是anaconda自带的,Image.open打开来的是图像格式,cv2是opencv的Python版本,cv2.imread读取出来的是像素格式。

PIL读取、保存图片

#! /usr/bin/env python3
# -*- coding:utf-8 -*-

# Author   : MaYi
# Blog     : http://www.cnblogs.com/mayi0312/
# Date     : 2020-09-29
# Name     : test.py
# Software : PyCharm
# Note     : 用于PIL&cv2相互转换
from PIL import Image


img = Image.open(img_name)

img.save(new_img_name, dpi=DPI)

CV2读取、保存图片

#! /usr/bin/env python3
# -*- coding:utf-8 -*-

# Author   : MaYi
# Blog     : http://www.cnblogs.com/mayi0312/
# Date     : 2020-09-29
# Name     : test.py
# Software : PyCharm
# Note     : 用于PIL&cv2相互转换
import cv2
import numpy as np

img = cv2.imread(img_name)  # 文件名不支持中文字符
# img = cv2.imdecode(np.fromfile(img_name, dtype=np.uint8), cv2.IMREAD_COLOR)

cv2.imwrite(new_img_name, img)  # 文件名不支持中文字符
# cv2.imencode('.tif', img)[1].tofile(new_img_name)

PIL转换为cv2

#! /usr/bin/env python3
# -*- coding:utf-8 -*-

# Author   : MaYi
# Blog     : http://www.cnblogs.com/mayi0312/
# Date     : 2020-09-29
# Name     : test.py
# Software : PyCharm
# Note     : 用于PIL&cv2相互转换
import cv2
import numpy as np
from PIL import Image

image = Image.open(img_name)
img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)

cv2转换为PIL

#! /usr/bin/env python3
# -*- coding:utf-8 -*-

# Author   : MaYi
# Blog     : http://www.cnblogs.com/mayi0312/
# Date     : 2020-09-29
# Name     : test.py
# Software : PyCharm
# Note     : 用于PIL&cv2相互转换
import cv2
from PIL import Image

image = cv2.imread(img_name)
img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

 

posted @ 2022-09-29 09:30  骑着螞蟻流浪  阅读(918)  评论(0编辑  收藏  举报