from PIL import Image import numpy as np from google.cloud import storage import os from firebase_admin import db from get_mask import get_mask import cv2 def make_area_estimate_image(arr, w, h, study_uid, study_field_id, pred_vals): num = 0 new_img = [[0]*w]*h row = 0 column = 0 storage_client = storage.Client() bucket_name = 'farmbase-b2f7e.appspot.com' map_fields = db.reference('PaidMonitoredFields').child('PMF').child(study_uid).child(study_field_id).get() coordinates = map_fields["Coordinates"] fieldmaxlat = map_fields["FieldMaxLat"] fieldminlat = map_fields["FieldMinLat"] fieldmaxlong = map_fields["FieldMaxLong"] fieldminlong = map_fields["FieldMinLong"] try: field_name = map_fields["FieldDescription"] except: field_name = map_fields["FieldAddress"] field_area = map_fields["FieldArea"] data = np.zeros((h,w,3), dtype=np.uint8) total_pixels = h*w area_pixels = 0 for i in arr: if i in pred_vals: data[row, column] = [0, 255,0] area_pixels = area_pixels + 1 new_img[row][column] = i column = column + 1 # total_pixels = total_pixels + 1 if column%w == 0: row = row+1 column = 0 #print(row, column) crop_area = (area_pixels/total_pixels)*int(field_area) crop_area = int(crop_area/10000) print((field_name + ' Area: ' + str(int(field_area/10000)) + ' Ha, Crop Area: ' + str(crop_area) + ' Ha')) img = Image.fromarray(data, 'RGB') file_name = study_uid + '/area_estimation.png' isdir = os.path.isdir(study_uid) if isdir != True: os.mkdir(study_uid) img.save(file_name) latestDay = 0 lastDayRef = db.reference('PaidMonitoredFields').child('PMF').child(study_uid).child(study_field_id).child('SensedDays').get() try: for (x,y) in lastDayRef.items(): if int(x) > int(latestDay): latestDay = x except: latestDay = 10101010 db.reference('PaidMonitoredFields').child('PMF').child(study_uid).child(study_field_id).child('SensedDays').child(str(latestDay)).set("yes") latestDay = str(latestDay) destination_blob_name_dem = 'PaidMonitoredFields/'+study_uid+'/'+study_field_id+'/'+latestDay+'/hybrid' dem_file_name = file_name #get_mask(study_uid,study_field_id,coordinates,fieldmaxlat,fieldminlat,fieldmaxlong,fieldminlong) img = cv2.imread(dem_file_name) kernel_int = 1 kernel = np.ones((kernel_int, kernel_int), np.uint8) opening = img i = 0 while i < 1: opening = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) opening = cv2.morphologyEx(opening, cv2.MORPH_OPEN, kernel) i = i + 1 # # kernel = np.ones((1,1), np.uint8) #opening = cv2.erode(opening, kernel, iterations = 1) cv2.imwrite(dem_file_name, opening) get_mask(study_uid,study_field_id,coordinates,fieldmaxlat,fieldminlat,fieldmaxlong,fieldminlong) bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name_dem) blob.upload_from_filename(dem_file_name) #print(new_img)