import cv2 import numpy as np import os def load_images(folder): images = [] file_names = [] for filename in os.listdir(folder): file_names.append(filename) file_names.sort() for filename in file_names: img = cv2.imread(os.path.join(folder, filename)) if img is not None: images.append(img) return images, file_names def tree_uprooting_detection(images, file_names, polygon_id): uprooting_dates = [] for i in range(1, len(images)): img1_gray = cv2.cvtColor(images[i - 1], cv2.COLOR_BGR2GRAY) img2_gray = cv2.cvtColor(images[i], cv2.COLOR_BGR2GRAY) diff = cv2.absdiff(img1_gray, img2_gray) _, thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY) kernel = np.ones((3, 3), np.uint8) dilated = cv2.dilate(thresh, kernel, iterations=3) contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: (x, y, w, h) = cv2.boundingRect(contour) area = cv2.contourArea(contour) print(('area: ' + str(area))) # Assuming an uprooted tree will result in a minimum of 100 square meters of change if area >= 2500: print(file_names[i]) uprooting_dates.append(file_names[i]) isdir = os.path.isdir('Uprooting') if isdir != True: os.mkdir('Uprooting') isdir = os.path.isdir(('Uprooting/' + polygon_id)) if isdir != True: os.mkdir(('Uprooting/' + polygon_id)) cv2.imwrite(('Uprooting/' + polygon_id + '/' + file_names[i]),images[i]) #return True return uprooting_dates def main(uid, polygon_id): folder = 'path/to/your/satellite/images' folder = uid + '/' + polygon_id images, file_names = load_images(folder) print(file_names) uprooting_dates = tree_uprooting_detection(images, file_names, polygon_id) return uprooting_dates # print('yes') # else: # print('no') if __name__ == '__main__': main()