参考:https://blog.csdn.net/haveanybody/article/details/86494063
cv2 打开图片,tensor的shape是(im_height, im_width, channel),BGR格式。cv2.imread返回的是numpy.ndarray张量。
pillow 打开图片,RGB格式。Pillow读出来的是PIL.Image.Image对象。
python##PIL 读取、保存图片方法
from PIL import Image
img = Image.open("eee.jpg")
img.save("eee_result.jpg")
##cv2 读取、保存图片方法
import cv2
img = cv2.imread("eee.jpg")
cv2.imwrite("eee_result.jpg", img)
##图片文件打开为base64
import base64
def img_base64(img_path):
with open(img_path, "rb") as f:
base64_str = base64.b64encode(f.read())
return base64_str
pythonfrom matplotlib import pyplot as plt
import cv2
img = cv2.imread("eee.jpg")
cv2.imwrite("eee_result.jpg", img)
imgrgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(imgrgb)
plt.show()
python## PIL转cv2
import cv2
from PIL import Image
import numpy as np
img_rgb = Image.open("eee.jpg")
img_bgr = cv2.cvtColor(np.asarray(img_rgb), cv2.COLOR_RGB2BGR) # 成为cv2的numpy.ndarray
python## PIL转cv2
import cv2
from PIL import Image
img_bgr = cv2.imread("eee.jpg")
img_rgb = Image.fromarray(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)) # 成为Pillow的PIL.Image.Image对象
python##PIL转base64
import base64
from io import BytesIO
from PIL import Image
def pillow_to_base64(image):
img_buffer = BytesIO()
image.save(img_buffer, format='JPEG')
byte_data = img_buffer.getvalue()
base64_str = base64.b64encode(byte_data)
return base64_str
# example
img = Image.open("eee.jpg")
print(pillow_to_base64(img))
python##PIL转base64
import base64
from io import BytesIO
from PIL import Image
def base64_to_pillow(base64_str):
image = base64.b64decode(base64_str)
image = BytesIO(image)
image = Image.open(image)
return image
# example
with open("eee.jpg", "rb") as f:
base64_str = base64.b64encode(f.read())
print(base64_to_pillow(base64_str))
python# cv2 转 base64
import base64
import cv2
def cv2_to_base64(image):
base64_str = cv2.imencode('.jpg', image)[1].tostring()
base64_str = base64.b64encode(base64_str)
return base64_str
# example
image = cv2.imread("eee.jpg")
print(cv2_to_base64(image))
python# base64 转 cv2
import base64
import numpy as np
import cv2
from PIL import Image
from io import BytesIO
def base64_to_cv2(base64_str):
imgString = base64.b64decode(base64_str)
nparr = np.frombuffer(imgString, np.uint8)
image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return image
# example
with open("eee.jpg", "rb") as f:
base64_str = base64.b64encode(f.read())
print(base64_to_cv2(base64_str))
pythonimg = cv2.imdecode(np.frombuffer(file, dtype=np.uint8), cv2.IMREAD_COLOR)
pythonimg = cv2.imdecode(np.fromstring(fileb.file.read(), np.uint8), cv2.IMREAD_COLOR)
参考:https://blog.csdn.net/sinat_29957455/article/details/107208432
pythonimg = cv2.imread("lpr1.png")
# 对数组的图片格式进行编码
success, encoded_image = cv2.imencode(".jpg", img)
# 将数组转为bytes
f = encoded_image.tobytes()
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!