카테고리 없음
openCV 이미지 회전, 반전, 저장, 흑백 변환
미친토끼
2024. 10. 23. 21:06
# numpy를 사용하여 이미지 3차원 배열을 회전하거나 반전함.
# 참고: https://numpy.org/devdocs/reference/generated/numpy.rot90.html
# np.rot90 = 회전, np.fliplr np.flipud = 좌우 반전, 상하 반전 fliplr=flip-left-right, flipud=flip-up-down
import numpy as np
import cv2
img = cv2.imread('img3.jpg')
# 시계 반대 방향 회전 1=90도, 2=180도, 3=270도
img_90 = np.rot90(img, 1)
img_180 = np.rot90(img, 2)
img_270 = np.rot90(img, 3)
cv2.imshow('img', img)
cv2.imshow('img_90', img_90)
cv2.imshow('img_180', img_180)
cv2.imshow('img_270', img_270)
# 시계 방향 회전 1=90도, 2=180도, 3=270도
img_90_reverse = np.rot90(img, -1)
img_180_reverse = np.rot90(img, -2)
img_270_reverse = np.rot90(img, -3)
cv2.imshow('img_reverse_90', img_90_reverse)
cv2.imshow('img_reverse_180', img_180_reverse)
cv2.imshow('img_reverse_270', img_270_reverse)
# 상하 반전
img_vertical = np.flipud(img) # np.flip(m, 0)과 동일
img_horizontal = np.fliplr(img) # np.flip(m, 1)과 동일
cv2.imshow('img_vertical', img_vertical)
cv2.imshow('img_horizontal', img_horizontal)
# 흑백 변환
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 파일 저장
result = cv2.imwrite('img_save.jpg', img_gray)
print(result) # 쓰기 성공했을 시 True 반환
cv2.waitKey(0)
cv2.destroyAllWindows()