图片各类格式转化

打开图片与保存图片

##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

CV2中的 BGR转RGB

from 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()


pillow CV2 的相互转换

## 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


PIL base64 的相互转换

##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))

##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))


CV2 base64 的相互转换

# 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))


# 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))


FastAPI中bytes 转CV2

img = cv2.imdecode(np.frombuffer(file, dtype=np.uint8), cv2.IMREAD_COLOR)

FastAPI中uploadfile 转CV2

img = cv2.imdecode(np.fromstring(fileb.file.read(), np.uint8), cv2.IMREAD_COLOR)

CV2 numpy 转成 字节流(open(“file.jpg”,‘rb’))

img = cv2.imread("lpr1.png")
# 对数组的图片格式进行编码
success, encoded_image = cv2.imencode(".jpg", img)
# 将数组转为bytes
f = encoded_image.tobytes()

to_show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            to_show = Image.fromarray(np.uint8(to_show))  # numpy.ndarray 转 PIL.Image.Image
            bytes_io = io.BytesIO()  # 将图片转为bytesio发送出去
            to_show.save(bytes_io, format="PNG")

            estimate = process(bytes_io.getvalue(), backend)
            estimated_image = Image.open(io.BytesIO(estimate.content)).convert("RGB")
            image_placeholder.image(to_show, caption='Video')  # 原图片 将图片帧展示在同一位置得到视频效果
            result_place.image(estimated_image, caption='Video')  # 结果图片 将图片帧展示在同一位置得到视频效果

 
img = Image.open(io.BytesIO(image_bytes))

        results = model(img, size=640)  # reduce size=320 for faster inference
        return results.pandas().xyxy[0].to_json(orient="records")

参考文章

  • https://codeantenna.com/a/syiFxEejDG
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以通过使用不同的库来实现各类文件格式之间的转换。以下是一些常用的库和示例代码: 1. 将文本文件转换为PDF: ```python from fpdf import FPDF def text_to_pdf(input_file, output_file): pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) with open(input_file, "r") as file: for line in file: pdf.cell(0, 10, txt=line, ln=True) pdf.output(output_file) input_file = "input.txt" output_file = "output.pdf" text_to_pdf(input_file, output_file) ``` 2. 将Word文档转换为PDF: ```python from docx2pdf import convert input_file = "input.docx" output_file = "output.pdf" convert(input_file, output_file) ``` 3. 将图片文件转换为PDF: ```python from PIL import Image def images_to_pdf(input_files, output_file): images = [] for file in input_files: image = Image.open(file) images.append(image.convert("RGB")) images.save(output_file, save_all=True, append_images=images[1:]) input_files = ["image1.jpg", "image2.png"] output_file = "output.pdf" images_to_pdf(input_files, output_file) ``` 4. 将Excel文件转换为PDF: ```python import pandas as pd from fpdf import FPDF def excel_to_pdf(input_file, output_file): df = pd.read_excel(input_file) table = df.to_html(index=False) pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.write_html(table) pdf.output(output_file) input_file = "input.xlsx" output_file = "output.pdf" excel_to_pdf(input_file, output_file) ``` 请根据你的需求选择适合的库和代码进行文件格式转换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值