Introduction: Deploy the normal image to sketch function service in the Alibaba Cloud Serverless Function Compute service to automatically convert images uploaded in batches to a specified OSS bucket into sketch images and save them to another OSS bucket
scene introduction
Xiao Ming received a task arranged by the school teacher and needed to convert ordinary photos taken by students in the class into sketches in batches for use in classroom games, so he asked the programmer's father for help. The witty programmer's father uses a few lines of Python every minute. Code solution: Deploy the normal image to sketch function service in the Alibaba Cloud Serverless Function Compute service to automatically convert images uploaded in batches to a specified OSS bucket into sketch images and save them to another OSS bucket.
target audience
An individual developer who understands Alibaba Cloud Serverless, OSS, and FC products, has some practical experience in cloud computing and Python programming, and is familiar with Alibaba Cloud authentication system and image processing OpenCV library.
Related concepts
Serverless: The full name of Serverless computing is serverless computing. It is a new model of cloud computing, which is different from traditional IaaS, PaaS, and SaaS. Serverless computing does not mean that it really does not need services, but that ordinary developers do not need to think too much about servers, app running environments and various peripheral dependencies, and computing resources truly become a service rather than a server or container. It allows developers to manage deployment and operation and maintenance at the granularity of managing a specific function, so that developers can focus on core business logic and develop applications more quickly.
Function Compute: The serverless mentioned above is a higher level of abstraction. "FaaS + BaaS" is an implementation of the serverless architecture model. Alibaba Cloud Function Compute is a typical FaaS. It cooperates with Alibaba Cloud's rich BaaS (SLS, OSS, RDS, etc.) services, which can deploy applications very quickly. FC is an event-driven fully managed computing service. Users do not need to purchase and manage infrastructure such as servers, but only need to write and upload code. FC uses computing and storage resources to run tasks elastically and reliably, and provides functions such as log query, performance monitoring, and alarming.
Prerequisites/Environmental Preparation
1. Alibaba Cloud FC, OSS, SLS services have been activated
2. Prepare the Python code for converting ordinary pictures into sketches in advance
3. Prepare test pictures in advance
4. Create two OSS buckets for testing in advance (the converted images cannot be uploaded to the same OSS bucket, which will cause the function to be executed in an infinite loop)
Steps
Step 1: Create a Function Compute FC service
- Select the function and service, click "Create Service", and fill in the name and description:
- Enter the function management, click "Create function":
Select Python 3.6 for the operating environment, use sample code for the code upload method, and process event requests for the request handler type.
Select OSS for trigger, and select sketch-image-input created in advance for Bucket. The file suffix is .jpg to prevent other types of files from accidentally triggering function execution after uploading.
Authorization role - Test the Python functions provided by default and familiarize yourself with the basic functions:
Step 2: Write a Python script to convert ordinary pictures to sketch functions
In the editor, enter the pre-written Python code:
The reference code is as follows:# -*- coding: utf-8 -*- import cv2 import json import logging import oss2 def sketch_image(source_image, target_image): # read image image = cv2.imread(source_image) # sketch image grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) invert_image = cv2.bitwise_not(grey_image) gaussian_blur_image = cv2.GaussianBlur(invert_image, (7, 7), 0) inverse_image = cv2.bitwise_not(gaussian_blur_image) sketch_image_result = cv2.divide(grey_image, inverse_image, scale=256.0) # save image cv2.imwrite(target_image, sketch_image_result) cv2.waitKey(0) cv2.destroyAllWindows() def handler(event, context): logger = logging.getLogger() evt = json.loads(event) creds = context.credentials # Required by OSS sdk auth=oss2.StsAuth( creds.access_key_id, creds.access_key_secret, creds.security_token) evt = evt['events'][0] bucket_name = evt['oss']['bucket']['name'] endpoint = 'oss-' + evt['region'] + '.aliyuncs.com' bucket_input = oss2.Bucket(auth, endpoint, bucket_name) bucket_output = oss2.Bucket(auth, endpoint, 'sketch-image-ouput') logger.info('oss endpoint: %s' % endpoint) objectName = evt['oss']['object']['key'] logger.info('oss objectName: %s' % objectName) newKey = 'sketch_' + objectName # Download image source_image = '/tmp/%s' % objectName bucket_input.get_object_to_file(objectName, source_image) logger.info('download image %s success.' % source_image) # Sketch image target_image = '/tmp/%s' % newKey sketch_image(source_image, target_image) # Upload image with open(target_image, 'rb') as fileobj: bucket_output.put_object(newKey, fileobj) logger.info('upload image %s success.' % newKey)
In the process of writing the function, I refer to the SDK case provided by Alibaba Cloud, which is very rich in content and has all the desired functions. Moreover, the Python operating environment provided by FC has built-in common modules such as oss and OpenCV, which can well support ordinary developers to quickly implement functions. , like👍🏻:
FC uses OSS trigger SDK: https://help.aliyun.com/document_detail/74765.html
OSS file download and upload SDK: https://help.aliyun.com/document_detail/88426.html
FC Python environment built-in modules: https://help.aliyun.com/document_detail/158208.htmlDeploy the code and activate the SLS log service, which is really convenient to view the log when debugging the code 😄:
Scheme verification
1. Upload the local test image to the OSS sketch-image-input bucket:
2. Observe the call log information and monitoring information of the function sketch_image:
3. Check the converted sketch image in the OSS sketch-image-output bucket, the effect is not bad😄:
4. Batch upload image test, the function is very stable👍🏻:
For more content, pay attention to the Serverless WeChat official account (ID: serverlessdevs), which brings together the most comprehensive content of serverless technology, regularly holds serverless events, live broadcasts, and user best practices.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。