diff --git a/solutions/sem02/lesson04/task1.py b/solutions/sem02/lesson04/task1.py index 1b5526c1..94941f59 100644 --- a/solutions/sem02/lesson04/task1.py +++ b/solutions/sem02/lesson04/task1.py @@ -2,16 +2,43 @@ def pad_image(image: np.ndarray, pad_size: int) -> np.ndarray: - # ваш код - return image - - -def blur_image( - image: np.ndarray, - kernel_size: int, -) -> np.ndarray: - # ваш код - return image + if pad_size < 1: + raise ValueError + + elif image.ndim == 2: + h, w = image.shape + new_h = h + pad_size * 2 + new_w = w + pad_size * 2 + + padded = np.zeros((new_h, new_w), dtype=image.dtype) + padded[pad_size : pad_size + h, pad_size : pad_size + w] = image + + elif image.ndim == 3: + h, w, c = image.shape + new_h = h + pad_size * 2 + new_w = w + pad_size * 2 + + padded = np.zeros((new_h, new_w, c), dtype=image.dtype) + padded[pad_size : pad_size + h, pad_size : pad_size + w, :] = image + + return padded + + +def blur_image(image: np.ndarray, kernel_size: int) -> np.ndarray: + if kernel_size % 2 == 0 or kernel_size < 1: + raise ValueError + if kernel_size == 1: + return image + + padding = kernel_size // 2 + padded = pad_image(image, padding) + shifted = [ + padded[i : i + image.shape[0], j : j + image.shape[1], ...] + for i in range(kernel_size) + for j in range(kernel_size) + ] + blurred = np.mean(shifted, axis=0) + return blurred.astype(image.dtype) if __name__ == "__main__": diff --git a/solutions/sem02/lesson04/task2.py b/solutions/sem02/lesson04/task2.py index be9a2288..8a4c300c 100644 --- a/solutions/sem02/lesson04/task2.py +++ b/solutions/sem02/lesson04/task2.py @@ -5,6 +5,25 @@ def get_dominant_color_info( image: np.ndarray[np.uint8], threshold: int = 5, ) -> tuple[np.uint8, float]: - # ваш код + if threshold < 1: + raise ValueError("threshold must be positive") - return 0, 0 + pixels = image.flatten() + counts = np.zeros(256, dtype=np.int64) + for color in range(256): + mask = pixels == color + counts[color] = np.sum(mask) + + max_pixels = 0 + best_color = 0 + for color in range(256): + if counts[color] != 0: + low = max(0, color - threshold + 1) + high = min(255, color + threshold - 1) + pixels = np.sum(counts[low : high + 1]) + + if pixels > max_pixels: + max_pixels = pixels + best_color = color + + return np.uint8(best_color), (max_pixels / pixels.size) * 100