Replies: 1 comment
-
以下是实现颜色扰动和随机旋转的完整 Python 代码: import cv2
import numpy as np
import random
def random_color_jitter(image, brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2):
"""
随机颜色扰动,包括亮度、对比度、饱和度和色调
"""
img = image.astype(np.float32) / 255.0
# 亮度调整
factor = 1.0 + random.uniform(-brightness, brightness)
img *= factor
# 对比度调整
factor = 1.0 + random.uniform(-contrast, contrast)
mean = np.mean(img, axis=(0, 1), keepdims=True)
img = (img - mean) * factor + mean
# 饱和度调整
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
factor = 1.0 + random.uniform(-saturation, saturation)
hsv[:, :, 1] *= factor
# 色调调整
factor = random.uniform(-hue, hue) * 179
hsv[:, :, 0] = (hsv[:, :, 0] + factor) % 179
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
return np.clip(img * 255.0, 0, 255).astype(np.uint8)
def random_rotate(image, angle_range=(-30, 30)):
"""
随机旋转图像
"""
h, w = image.shape[:2]
angle = random.uniform(angle_range[0], angle_range[1])
# 计算旋转矩阵
M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)
rotated_image = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
return rotated_image
def augment_image(image_path):
"""
读取图像, 进行颜色扰动和随机旋转, 最后返回处理后的图像
"""
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 转换为RGB格式以符合OpenCV的标准
image = random_color_jitter(image)
image = random_rotate(image)
return cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # 转换回BGR以便OpenCV显示
# 示例:
if __name__ == "__main__":
img_path = "input.jpg" # 替换为你的图片路径
augmented_img = augment_image(img_path)
cv2.imwrite("output.jpg", augmented_img) # 保存结果
cv2.imshow("Augmented Image", augmented_img)
cv2.waitKey(0)
cv2.destroyAllWindows() 代码说明:
你可以调整 Response generated by 🤖 feifei-bot | chatgpt-4o-latest |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
发python完整代码,颜色扰动,随机旋转
Beta Was this translation helpful? Give feedback.
All reactions