from PIL import Image import traceback from google.cloud import storage from oauth2client.service_account import ServiceAccountCredentials import os import traceback def upload_hybrid(uid, fieldid, imagedate): source_url = uid + '/' + fieldid + '/hybrid.png' storage_client = storage.Client.from_service_account_json('servicekey.json') bucket_name = 'farmbase-b2f7e.appspot.com' destination_blob_name = 'PaidMonitoredFields/' + uid + '/' + fieldid + '/' + str(imagedate) + '/hybrid' bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) try: blob.upload_from_filename(source_url) except: print(traceback.format_exc()) def create_hybrid_image(rvi_path, rsm_path, hybrid_path, uid, fieldid, imagedate): # Define the hex color codes to be used in the logic try: green_hex_codes = ['#06653d', '#11A75F', '#81bf6c', '#bae383', '#e6f3a4'] red_hex_codes = ['#fbc07e', '#f7885a', '#ea4f3b', '#fff0b5'] white_hex_code = '#ab0535' # Open the two images with alpha channels rvi = Image.open(rvi_path).convert('RGBA') rsm = Image.open(rsm_path).convert('RGBA') # Ensure the images are of the same size if rvi.size != rsm.size: raise ValueError("The images rvi.png and rsm.png must be of the same size.") # Create a new image with the same size and mode 'RGBA' hybrid = Image.new('RGBA', rvi.size) # Get the pixel data rvi_pixels = rvi.load() rsm_pixels = rsm.load() hybrid_pixels = hybrid.load() width, height = rvi.size for x in range(width): for y in range(height): rvi_pixel = rvi_pixels[x, y] rsm_pixel = rsm_pixels[x, y] rvi_pixel_hex = '#%02x%02x%02x' % rvi_pixel[:3] rsm_pixel_hex = '#%02x%02x%02x' % rsm_pixel[:3] rvi_alpha = rvi_pixel[3] if rvi_alpha == 0: # If the pixel in rvi.png has zero alpha, set it in hybrid.png too hybrid_pixels[x, y] = (0, 0, 0, 0) elif rvi_pixel_hex in green_hex_codes and rsm_pixel_hex in green_hex_codes: hybrid_pixels[x, y] = (17, 167, 95, rvi_alpha) # #11A75F elif rvi_pixel_hex in red_hex_codes and rsm_pixel_hex in red_hex_codes: hybrid_pixels[x, y] = (145, 16, 44, rvi_alpha) # #91102C elif rvi_pixel_hex == white_hex_code and rsm_pixel_hex == white_hex_code: hybrid_pixels[x, y] = (255, 255, 255, rvi_alpha) # #FFFFFF elif rvi_pixel_hex in red_hex_codes and rsm_pixel_hex not in red_hex_codes: hybrid_pixels[x, y] = (247, 136, 90, rvi_alpha) # #F7885A elif rsm_pixel_hex in red_hex_codes and rvi_pixel_hex not in red_hex_codes: hybrid_pixels[x, y] = (60, 19, 97, rvi_alpha) # #3C1361 else: # If none of the conditions match, use a default color (optional) hybrid_pixels[x, y] = (17, 167, 95, rvi_alpha) # Black with rvi alpha value # Save the new hybrid image hybrid.save(hybrid_path) upload_hybrid(uid, fieldid, imagedate) # Call the function to create the hybrid image #create_hybrid_image() except: print(traceback.format_exc())