Image Encoding

Function Description

Encodes the Image object output by an API into a .jpg image or saves the Image object to a specified path.

For details about the API, see encode.

API Call Process

You can call the image decoding and processing APIs (for cropping, resizing, and padding) to obtain the Image object to be encoded, and call the Encode API of the ImageProcessor class to output the object to the memory or save it to the local host.

The process of calling image encoding APIs is as follows:

Figure 1 Process of calling image encoding APIs

Key steps are demonstrated as follows:

  1. Perform global initialization by calling mx_init().
  2. Initialize ImageProcessor.

    Construct the ImageProcessor object. You need to specify the device ID during the construction.

  3. Call the image decoding API to decode the input image.

    Decode the image based on services to generate a codable Image object. Subsequently, the image can be processed by using the image processing APIs to generate a final Image object to be encoded.

  4. Call the encode API to encode the input image.

    Output image data based on the specific service requirements and specify the image to be output and the output path.

  5. Perform deinitialization by calling mx_deinit().

Sample Code

The following is a code example of key steps of functions and features, which is for reference only and cannot be directly copied for execution.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from mindx.sdk import base  
from mindx.sdk.base import ImageProcessor, Rect, Image

def process():
    # Decode an image.
    # Initialize the ImageProcessor object.
    imageProcessor = ImageProcessor(device_id)  
    image_path = "image_data/test_image.jpg"  
    # Read the image path for decoding. The decoding format is nv12 (YUV_SP_420).
    decoded_image = imageProcessor.decode(image_path, base.nv12)  
   
    # Image processing (image cropping)
    crop_para = [Rect(300, 100, 550, 350)]  
    croped_images = imageProcessor.crop(decoded_image, crop_para)  

    # Image encoding
    image_save_path = "croped_image.jpg"  
    imageProcessor.encode(croped_images[0], image_save_path) 

if __name__ == "__main__":
    base.mx_init()     # Initialize resources.
    process()
    base.mx_deinit()   # Deinitialize resources.