压缩图片json文件也被压缩代码

本文介绍了一个Python脚本,用于读取图像文件和对应的JSON标注文件,通过调整图像大小并保持原始比例,同时更新JSON文件中的尺寸信息和Base64编码的图像数据。脚本适用于批量处理图像文件夹中的图片和标注文件。
摘要由CSDN通过智能技术生成
import os
import cv2
import numpy as np
import json
import base64

def resize_polygon(polygon, resize_factor):
    return [[int(point[0] * resize_factor), int(point[1] * resize_factor)] for point in polygon]

def resize_image_and_update_json(image, max_dimension, annotation_data):
    # Calculate the resize factor while maintaining the aspect ratio
    height, width = image.shape[:2]
    aspect_ratio = width / height

    if width > height:
        new_width = max_dimension
        new_height = int(max_dimension / aspect_ratio)
    else:
        new_height = max_dimension
        new_width = int(max_dimension * aspect_ratio)

    # Resize the image
    augmented_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)

    # Update image height and width in the JSON data
    annotation_data['imageHeight'] = augmented_image.shape[0]
    annotation_data['imageWidth'] = augmented_image.shape[1]

    # Encode the resized image to base64 and update "imageData" field
    _, encoded_image = cv2.imencode('.jpg', augmented_image)
    print(encoded_image.shape)
    annotation_data['imageData'] = base64.b64encode(encoded_image).decode('utf-8')



    # Resize polygon coordinates
    label_polygon = annotation_data['shapes'][0]['points']
    augmented_label_polygon = resize_polygon(label_polygon, max(new_width / width, new_height / height))

    return augmented_image, augmented_label_polygon



def process_images_in_folder(image_folder, json_folder, output_image_folder, output_json_folder):
    for filename in os.listdir(image_folder):
        if filename.endswith(('.jpg', '.jpeg', '.png')):
            image_path = os.path.join(image_folder, filename)
            json_path = os.path.join(json_folder, filename.replace('.jpg', '.json'))
            if os.path.isfile(json_path):
                try:
                    with open(json_path, 'r', encoding='utf-8') as f:
                        annotation_data = json.load(f)

                    # Check if 'shapes' list is not empty
                    if 'shapes' in annotation_data and annotation_data['shapes']:
                        label_polygon = annotation_data['shapes'][0]['points']
                        image = cv2.imread(image_path)

                        # Perform data augmentation and update JSON
                        augmented_image, augmented_label_polygon = resize_image_and_update_json(image, 640, annotation_data)

                        # Build paths and file names for saving
                        output_filename = filename.replace('.jpg', '_01.jpg')
                        output_image_path = os.path.join(output_image_folder, output_filename)
                        output_json_path = os.path.join(output_json_folder, output_filename.replace('.jpg', '.json'))

                        # Save the augmented image
                        cv2.imwrite(output_image_path, augmented_image)

                        # Update and save the augmented JSON file
                        annotation_data['shapes'][0]['points'] = augmented_label_polygon
                        with open(output_json_path, 'w') as f:
                            json.dump(annotation_data, f, indent=2)
                    else:
                        print(f"Warning: 'shapes' list is empty or does not exist in {json_path}")
                except json.decoder.JSONDecodeError as e:
                    print(f"Error reading JSON file {json_path}: {e}")
                    continue

# Example usage: Replace 'path_to_your_folders' with the actual folder paths
input_image_folder = 'E:\\nai_liang_ceshitupian\\2023-12-18'
input_json_folder = 'E:\\nai_liang_ceshitupian\\2023-12-18-json'
output_image_folder = 'E:\\nai_liang_ceshitupian\\2023-12-18-640'
output_json_folder = 'E:\\nai_liang_ceshitupian\\2023-12-18-640_json'
process_images_in_folder(input_image_folder, input_json_folder, output_image_folder, output_json_folder)
  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 首先,为了将图片传输给前端页面显示,需要将其编码为Base64字符串。在Qt中,可以通过使用QPixmap和QByteArray类来实现这一功能。QPixmap类可以用来加载图片文件,而QByteArray类则可以用来存储编码后的Base64字符串。 具体步骤如下: 1. 使用QPixmap类加载图片文件,例如: ```cpp QPixmap pixmap("path/to/image.jpg"); ``` 2. 将QPixmap对象转换为QImage对象,方便进行Base64编码,例如: ```cpp QImage image = pixmap.toImage(); ``` 3. 将QImage对象转换为QByteArray对象,进行Base64编码,例如: ```cpp QByteArray imageData; QBuffer buffer(&imageData); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "JPG"); QString base64Str = QString(imageData.toBase64()); ``` 这里需要将图片保存为JPG格式,因为在Base64编码中使用的是JPG格式。 4. 将Base64字符串发送给前端页面,在前端页面中对Base64字符串进行解码,然后将解码后的内容显示为图片。 以上就是在Qt中将图片编码为Base64字符串,并传输给前端页面显示的方法。需要注意的是,如果图片过大,会导致传输过程中的数据量增加,因此需要根据实际需求进行合理的压缩和优化。 ### 回答2: Qt是一种功能强大的跨平台应用程序框架,它可以轻松地与各种外部库和API进行集成。其中,使用Json格式传输数据已经成为了现代Web应用程序中最常见的方法之一。Json格式非常灵活,可以包含不同类型的数据,如字符串,数字和布尔值。除此之外,它还支持多种复杂数据类型,如数组和嵌套对象。 要在Qt中传输图片并在前端页面上显示,我们需要进行以下几个步骤: 1.首先,我们需要将图像文件读取到内存中。在Qt中,可以使用QImage类来完成这个任务。QImage类提供了许多方法和函数,可以轻松地将不同格式的图像文件读取到内存中。 2.接下来,我们需要将图像数据转换为字符串,在Json数据格式中传输。为此,可以使用QByteArray类来存储数据,并使用toBase64()方法将它们转换为字符串。这个的好处是可以避免特殊字符造成的问题。 3.将图像数据以JSON格式传输给前端需要使用Qt中的Json库。Qt中的Json库提供了多个类和方法,可以轻松地转换数据对象为Json格式,并且将Json格式数据解释/转换成其他类型的数据对象。 4.前端代码,将收到的Json格式数据转换回图像并在页面上显示。Node.js, jQuery, Vue.js,等框架都提供JSON数据解析和图像显示方法,我们可以根据所使用的框架和技术进行不同的实现。 总之,Qt与Json和图像处理技术的集成使得图像传输变得更加容易和灵活。同时,这也为我们提供了一种扩展和自定义应用程序的方法,使我们的应用程序更加具有适应性和可扩展性。 ### 回答3: Qt是一款流行的跨平台桌面应用程序开发框架,支持多种编程语言,如C++、Python等。同时,Qt也支持使用Json格式进行数据传输,Json是一种轻量级的数据交换格式。 在Qt中,如果想要传输图片给前端页面显示,可以使用Json格式进行传输。具体实现方法如下: 1. 将图片进行编码,可以使用Base64编码等方式。这样可以将图片转化成字符串格式,方便进行Json格式的传输。 2. 将编码后的图片字符串作为Json对象的一个属性值,将Json对象发送给前端页面。 3. 在前端页面中,使用JavaScript脚本解析Json对象,获取图片属性值。 4. 将获取到的图片属性值解码,即可得到原始的图片数据。 通过以上步骤,即可在前端页面中成功显示从Qt传输过来的图片。需要注意的是,在传输大图片时,可能会遇到网络传输缓慢的问题,可以考虑压缩图片大小,或在传输过程中进行分段传输等优化措施,以提高图片传输的效率和稳定性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值