0

0

使用 Protobuf 在 Python 中处理图像旋转

聖光之護

聖光之護

发布时间:2025-09-26 19:08:01

|

276人浏览过

|

来源于php中文网

原创

使用 protobuf 在 python 中处理图像旋转

本文档旨在指导开发者如何使用 Protobuf 定义的图像接口,在 Python 中实现图像的旋转功能。文章将详细介绍如何将 Protobuf 中以 bytes 类型存储的图像数据转换为可操作的矩阵形式,并提供完整的代码示例,帮助读者理解和应用图像旋转的实现方法。

在使用 Protobuf 进行图像处理时,一个常见的挑战是如何将以 bytes 类型传递的图像数据转换为可操作的格式,例如二维矩阵,以便进行旋转等操作。本文将详细介绍如何使用 Python 处理 Protobuf 定义的图像数据,并实现图像的旋转。

理解 Protobuf 图像定义

首先,我们需要理解 Protobuf 中图像的定义。根据提供的 .proto 文件,Image 消息包含以下字段:

  • color: 布尔类型,指示图像是彩色(RGB)还是灰度图像。
  • data: 字节类型,存储图像的原始数据。
  • width: 整数类型,图像的宽度。
  • height: 整数类型,图像的高度。

彩色图像的 data 字段以 RGB 三元组的形式逐行存储,而灰度图像则以单字节形式逐行存储。

立即学习Python免费学习笔记(深入)”;

将 Bytes 数据转换为矩阵

关键在于将 bytes 类型的 data 字段转换为 Python 中可操作的矩阵形式。以下代码展示了如何实现这一转换:

import grpc
import image_pb2
import image_pb2_grpc

from concurrent import futures

# gRPC service implementation
class ImageService(image_pb2_grpc.ImageServiceServicer):

    def RotateImage(self, request, context):

        # Ensure that the number of bytes matches expection: width*height*bytes(color)
        # Where bytes(color) = 1 (false) and 3 (true)
        got = request.image.width * request.image.height * (3 if request.image.color else 1)
        want = len(request.image.data)

        if got != want:
            context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
            context.set_details("Image data size does not correspond to width, height and color")
            return request.image

        # If there's no rotation to perform, shortcut to returning the provided image
        if request.rotation == image_pb2.ImageRotateRequest.NONE:
            return request.image

        # Convert the image to a matrix
        matrix = []
        current = 0
        for y in range(request.image.height):
            row = []
            for x in range(request.image.width):
                if request.image.color:
                    # True (RGB) requires 3 bytes (use tuple)
                    pixel = (
                        request.image.data[current],
                        request.image.data[current+1],
                        request.image.data[current+2],
                    )
                    current += 3
                else:
                    # False (Grayscale) requires 1 byte
                    pixel = request.image.data[current]
                    current += 1

                row.append(pixel)
            # Append row
            matrix.append(row)

        print(matrix)

        if request.rotation == image_pb2.ImageRotateRequest.NINETY_DEG:
            print("Rotating: 090")
            matrix = list(zip(*matrix[::-1]))

        if request.rotation == image_pb2.ImageRotateRequest.ONE_EIGHTY_DEG:
            print("Rotating: 180")
            matrix = list(zip(*matrix[::-1]))
            matrix = list(zip(*matrix[::-1]))

        if request.rotation == image_pb2.ImageRotateRequest.TWO_SEVENTY_DEG:
            print("Rotating: 270")
            # Rotate counterclockwise
            matrix = list(zip(*matrix))[::-1]

        # Flatten the matrix
        pixels = []
        for y in range(request.image.height):
            for x in range(request.image.width):
                    if request.image.color:
                        pixels.extend(matrix[y][x])
                    else:
                        pixels.append(matrix[y][x])


        print(f"Result: {pixels}")

        # Revert the flattened matrix to bytes
        data = bytes(pixels)

        # Return the rotated image in the response
        return image_pb2.Image(
            color=request.image.color,
            data=data,
            width=request.image.width,
            height=request.image.height,
        )


# gRPC server setup
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    image_pb2_grpc.add_ImageServiceServicer_to_server(ImageService(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    serve()

这段代码首先检查 data 字段的长度是否与图像的宽度、高度和颜色模式相符。如果不符,则返回错误。然后,它根据图像的颜色模式,将 data 字段转换为二维矩阵。彩色图像的每个像素由一个包含三个字节的元组表示,而灰度图像的每个像素由一个字节表示。

图像旋转

将图像数据转换为矩阵后,可以使用 Python 的列表操作进行旋转。以下代码展示了如何旋转矩阵:

        if request.rotation == image_pb2.ImageRotateRequest.NINETY_DEG:
            print("Rotating: 090")
            matrix = list(zip(*matrix[::-1]))

        if request.rotation == image_pb2.ImageRotateRequest.ONE_EIGHTY_DEG:
            print("Rotating: 180")
            matrix = list(zip(*matrix[::-1]))
            matrix = list(zip(*matrix[::-1]))

        if request.rotation == image_pb2.ImageRotateRequest.TWO_SEVENTY_DEG:
            print("Rotating: 270")
            # Rotate counterclockwise
            matrix = list(zip(*matrix))[::-1]

这段代码使用了 zip(*matrix[::-1]) 技巧来旋转矩阵。[::-1] 用于反转矩阵的行,zip(*...) 用于转置矩阵。

CSS3圆形图片鼠标经过旋转效果
CSS3圆形图片鼠标经过旋转效果

CSS3圆形图片鼠标经过旋转效果,图片上有简短标题和说明,兼容主流浏览器,php中文网推荐下载! 使用方法: 1、在head区域引入样式表文件lrtk.css 2、在你的网页中加入注释区域代码即可 3、图片为方形,宽高在220像素以上,并有一定空白边距效果较好。

下载

将矩阵转换回 Bytes 数据

旋转矩阵后,需要将其转换回 bytes 类型,以便将其存储在 Protobuf 的 data 字段中。以下代码展示了如何实现这一转换:

        # Flatten the matrix
        pixels = []
        for y in range(request.image.height):
            for x in range(request.image.width):
                    if request.image.color:
                        pixels.extend(matrix[y][x])
                    else:
                        pixels.append(matrix[y][x])


        print(f"Result: {pixels}")

        # Revert the flattened matrix to bytes
        data = bytes(pixels)

这段代码将矩阵扁平化为一个列表,然后使用 bytes() 函数将其转换为 bytes 类型。

示例

以下是一些使用 grpcurl 工具测试图像旋转服务的示例:

灰度图像旋转 180 度

# Want: [[1,2,3],[4,5,6],[7,8,9]]
# Byte: 010203040506070809
# B64: AQIDBAUGBwgJ
DATA="AQIDBAUGBwgJ"
COLOR=false

REQUEST="
{
    \"rotation\": 2,
    \"image\": {
        \"color\": ${COLOR},
        \"data\": \"${DATA}\",
        \"width\": 3,
        \"height\": 3
    }
}"

grpcurl \
-plaintext \
-proto image.proto \
-d "${REQUEST}" \
localhost:50051 \
ImageService/RotateImage \
| jq -r .data \
| base64 --decode \
| xxd -g 3

预期输出:

00000000: 090807 060504 030201
# Want: [[9,8,7],[6,5,4],[3,2,1]]

彩色图像旋转 180 度

# Want: [[010101,020202,030303], ... ]
# Byte: 010101020202030303...
# B64: AQEBAgICAwMDBAQEBQUFBgYGBwcHCAgICQkJ
DATA="AQEBAgICAwMDBAQEBQUFBgYGBwcHCAgICQkJ"
COLOR=true

REQUEST="
{
    \"rotation\": 2,
    \"image\": {
        \"color\": ${COLOR},
        \"data\": \"${DATA}\",
        \"width\": 3,
        \"height\": 3
    }
}"

grpcurl \
-plaintext \
-proto image.proto \
-d "${REQUEST}" \
localhost:50051 \
ImageService/RotateImage \
| jq -r .data \
| base64 --decode \
| xxd -g 3

预期输出:

00000000: 090909 080808 070707 060606 050505 04
00000010: 040403 030302 020201 0101
# Want [[090909, 080808, 070707], ... ]

注意事项

  • 在处理图像数据时,务必确保 data 字段的长度与图像的宽度、高度和颜色模式相符。
  • 图像旋转算法可能会改变图像的宽度和高度。在更新 Image 消息时,请确保正确设置宽度和高度字段。
  • 为了提高代码的可测试性,可以将矩阵处理逻辑提取到单独的函数中。

总结

本文档介绍了如何使用 Protobuf 定义的图像接口,在 Python 中实现图像的旋转功能。通过将 bytes 类型的 data 字段转换为可操作的矩阵形式,并使用 Python 的列表操作进行旋转,可以轻松实现图像的旋转。希望本文档能够帮助读者理解和应用图像旋转的实现方法。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
硬盘接口类型介绍
硬盘接口类型介绍

硬盘接口类型有IDE、SATA、SCSI、Fibre Channel、USB、eSATA、mSATA、PCIe等等。详细介绍:1、IDE接口是一种并行接口,主要用于连接硬盘和光驱等设备,它主要有两种类型:ATA和ATAPI,IDE接口已经逐渐被SATA接口;2、SATA接口是一种串行接口,相较于IDE接口,它具有更高的传输速度、更低的功耗和更小的体积;3、SCSI接口等等。

1180

2023.10.19

PHP接口编写教程
PHP接口编写教程

本专题整合了PHP接口编写教程,阅读专题下面的文章了解更多详细内容。

235

2025.10.17

php8.4实现接口限流的教程
php8.4实现接口限流的教程

PHP8.4本身不内置限流功能,需借助Redis(令牌桶)或Swoole(漏桶)实现;文件锁因I/O瓶颈、无跨机共享、秒级精度等缺陷不适用高并发场景。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

2158

2025.12.29

java接口相关教程
java接口相关教程

本专题整合了java接口相关内容,阅读专题下面的文章了解更多详细内容。

27

2026.01.19

页面置换算法
页面置换算法

页面置换算法是操作系统中用来决定在内存中哪些页面应该被换出以便为新的页面提供空间的算法。本专题为大家提供页面置换算法的相关文章,大家可以免费体验。

419

2023.08.14

go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

29

2026.01.31

go语言 math包
go语言 math包

本专题整合了go语言math包相关内容,阅读专题下面的文章了解更多详细内容。

17

2026.01.31

go语言输入函数
go语言输入函数

本专题整合了go语言输入相关教程内容,阅读专题下面的文章了解更多详细内容。

15

2026.01.31

golang 循环遍历
golang 循环遍历

本专题整合了golang循环遍历相关教程,阅读专题下面的文章了解更多详细内容。

3

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.4万人学习

Django 教程
Django 教程

共28课时 | 3.8万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.4万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号