def make_tiles(image_path, tile_size=1024, max_tiles=64, avg_thr=230, std_thr=15, clip_edge=0.05): image = pyvips.Image.new_from_file(image_path, access='sequential') # cropping offset_x = int(image.width * clip_edge) offset_y = int(image.height * clip_edge) w = int(image.width * (1-clip_edge*2)) h = int(image.height * (1-clip_edge*2)) image = image.crop(offset_x, offset_y, w, h) # padding pad_w = (tile_size - image.width%tile_size)%tile_size pad_h = (tile_size - image.height%tile_size)%tile_size image = image.embed( pad_w//2, pad_h//2, image.width+pad_w, image.height+pad_h, extend="mirror") # Get the scanning position of the image x_pos_list = [] y_pos_list = [] for y in range(0, image.height, tile_size): for x in range(0, image.width, tile_size): x_pos_list.append(x) y_pos_list.append(y) # Get the cropping position of the image selected_x_pos_list = [] selected_y_pos_list = [] avg_list = [] for x, y in zip(x_pos_list, y_pos_list): tile = image.crop(x, y, tile_size, tile_size) avg = tile.avg() std = tile.deviate() if avg < avg_thr and std > std_thr: selected_x_pos_list.append(x) selected_y_pos_list.append(y) avg_list.append(avg) # Sort by ascending order of average brightness sorted_idx = np.argsort(np.array(avg_list)) selected_x_pos_array = np.array(selected_x_pos_list)[sorted_idx][:max_tiles] selected_y_pos_array = np.array(selected_y_pos_list)[sorted_idx][:max_tiles] # crop images = [] for x, y in zip(selected_x_pos_array, selected_y_pos_array): tile = image.crop(x, y, tile_size, tile_size) img = tile.numpy() images.append(img) if len(images) > 0: images = np.stack(images) del image gc.collect() return images