in 3-photos/1-chromakey/app.py [0:0]
def lambda_handler(event, context):
print ("Starting handler")
# get object metadata from event
input_bucket_name = event['Records'][0]['s3']['bucket']['name']
file_key = event['Records'][0]['s3']['object']['key']
output_bucket_name = os.environ['OUTPUT_BUCKET_NAME']
output_file_key = file_key.replace('.jpg', '.png')
print("Input bucket: ", input_bucket_name)
print("Output bucket: ", output_bucket_name)
if output_bucket_name is None:
print("Error: No OUTPUT_BUCKET_NAME environment variable specified.")
return
# set up local temp file names
local_input_temp_file = '/tmp/' + file_key
local_output_temp_file = '/tmp/out_' + file_key.replace('.jpg', '.png')
logger.info('Local input file: {}'.format(local_input_temp_file))
logger.info('Local output file: {}'.format(local_output_temp_file))
# get the object
s3.download_file(input_bucket_name, file_key, local_input_temp_file)
# HSV range
# (36, 25, 25) - most extreme
# (36, 50, 50) - average
# (36, 100, 100) - relaxed
lower_range = tuple(json.loads(os.environ["HSV_LOWER"]))
# (70, 255, 255) - default
upper_range = tuple(json.loads(os.environ["HSV_UPPER"]))
print('Lower HSV range: ', lower_range)
print('Upper HSV range: ', upper_range)
# Read in the file
image = cv2.imread(local_input_temp_file)
# Resize the image if larger than target size
image = scale_image(image)
# Flip from RGB of JPEG to BGR of OpenCV
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Convert BGR to HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# convert to RGBA
image_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)
# Threshold the HSV image to only green colors
mask = cv2.inRange(hsv, lower_range, upper_range)
# Invert the mask (i.e. select everything not green)
mask = ~mask
# Extract the non-green parts of the image
result = cv2.bitwise_and(image_alpha, image_alpha, mask=mask)
#Save the result
cv2.imwrite(local_output_temp_file,result)
#Save to S3
if upload_file(local_output_temp_file, output_bucket_name, output_file_key):
print('Processed file uploaded.')
return True