Files
task-3-1-3-Matrix-Fundament…/260416-2509165039.py
2026-04-16 15:53:22 +08:00

74 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 练习1图像矩阵操作
import numpy as np
image = np.array([
[100, 150, 200],
[80, 120, 180],
[60, 90, 140]
], dtype=np.uint8)
print("原图:")
print(image)
image_dark = image - 20
print("\n变暗20后的图像:")
print(image_dark)
image_crop = image[0:2,0:2]
print("\n裁剪左上角后的图像:")
print(image_crop)
image_flip = np.fliplr(image)
print("\n水平翻转后的图像:")
print(image_flip)
# 练习2看图写代码
import numpy as np
img = np.array([
[255, 255, 0, 0 ],
[255, 255, 0, 0 ],
[0, 0, 255, 255],
[0, 0, 255, 255]
], dtype=np.uint8)
print("原始图像:")
print(img)
white_pixel_count = np.sum(img == 255)
black_pixel_count = np.sum(img == 0)
print(f"\n白色像素(255)的数量:{white_pixel_count}")
print(f"黑色像素(0)的数量:{black_pixel_count}")
flipped_img_horizontal = img[:,::-1]
print("\n水平翻转后的图像:")
print(flipped_img_horizontal)
rotated_img_ccw = img.T[:,::-1]
print("\n逆时针旋转90度后的图像:")
print(rotated_img_ccw)
# 练习3特征向量计算
import numpy as np
# 假设这是从图像中提取的2个特征图
feature_map1 = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
feature_map2 = np.array([[1, 1, 1], [1, 0, 0], [1, 0, 0]])
# 补全代码:将特征图展平为向量
vector1 = feature_map1.flatten() # 展平
vector2 = feature_map2.flatten() # 展平
print("vector1:", vector1)
print("vector2:", vector2)
euclidean_distance = np.linalg.norm(vector1 - vector2)
print("\n欧几里得距离:",euclidean_distance)
cosine_similarity = np.dot(vector1,vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2))
print("余弦相似度:",cosine_similarity)