import time starttime = time.time() image = cv2.imread("0.6/01.pgm", cv2.COLORBGR2GRAY)…
- User
import time
start_time = time.time()
image = cv2.imread("0.6/01.pgm", cv2.COLOR_BGR2GRAY)
IMAGE_THRESHOLD = 100
def count_zero_pixels(image): zero_pixels = np.count_nonzero(image == 0) return zero_pixels
def calculate_zero_pixel_percentage(image): total_pixels = image.size zero_pixels = count_zero_pixels(image) zero_percentage = zero_pixels / total_pixels * 100 return zero_percentage
zero_percentage = calculate_zero_pixel_percentage(image)
if zero_percentage > 75: IMAGE_THRESHOLD = 0
print(f"image_threshold: {IMAGE_THRESHOLD}") print(f"Процент зануленных пикселей относительно всех пикселей: {zero_percentage}%")
def get_coords_by_threshold( image: np.ndarray, threshold: int = IMAGE_THRESHOLD ) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords
def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image
def get_neigh_nums_list( coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2
for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > image.shape[0] - offset: continue if y < 0 + offset or y > image.shape[1] - offset: continue kernel = image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_numsdef get_neigh_coeffs_list( coords: tuple, kernel: np.array ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's coeffs. """ neigh_coeffs = []
offset = (kernel.shape[0] - 1) // 2 print(offset) for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > image.shape[0] - offset: continue if y < 0 + offset or y > image.shape[1] - offset: continue try: image_kernel = image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_coeff = np.sum(kernel * image_kernel) neigh_coeffs.append([x, y, step_neigh_coeff]) except ValueError as e: continue return neigh_coeffsdef sort_neight_nums_by_N(neigh_nums: list) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums)
np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums - Assistant