import cv2
# imread : 이미지 불러오기
image = cv2.imread("이미지 파일 경로")
# 이 부분을 하드코딩하지 않으려고 argparse 사용가능
"""
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("i", "--image", required=True, help="path to input image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
"""
# imshow : 이미지 출력
cv2.imshow("이미지이름", image)
# imwrite : 이미지 저장
cv2.imwrite("새로 저장할 이미지 경로", image)
(2) 이미지 getting, setting
# 이미지 형태 추출
(h, w) = image.shape[:2]
(h, w, c) = image.shape[:3]
# 이미지의 특정 픽셀[(0,0)-왼쪽위 모서리] RGB 정보 추출
(b,g,r) = image[0,0]
# Pixel at (50, 20)을 Red로 변경
image[20,50] = (0,0,255)
# 이미지 왼쪽 상단을 초록색으로 변경
image[0:h//2, 0:w//2] = (0, 255, 0)
* OpenCV에서 주의할 부분 *
1. 가로세로 순서 주의하기 : (세로,가로,채널) 순서임 (height, width, channel) = image.shape[:3] image[20,50] = pixel located at x=50, y=20
2. RBG도 (b,g,r) 순서임
(3) drawing
# 3채널의 300*300크기 캔버스를 black 배경으로 생성
canvas = np.zeros((300,300,3), dtype='uint8')
# 선, 도형 그리기
cv2.line(canvas, (0,0), (300,300), green)
cv2.rectangle(canvas, (10,10), (60,60), green)
cv2.rectangle(canvas, (10,10), (60,60), green, 5) # 굵기가 5 pixel
cv2.rectangle(canvas, (10,10), (60,60), green, -1) # 내부 색상 채우기
cv2.rectangle(canvas, (10,10), (60,60), green, cv2.FILLED) # 내부 색상 채우기
cv2.circle(canvas, (centerX, centerY), r, white, pixel)
(4) 이동시키기(translate)
1. OpenCV : 변환행렬 생성 + cv2.warpAffine 함수 사용하기
2. imutils : translater 함수 사용하기
* shiftX, shiftY가 양수일때 : 오른쪽, 아래로 이동
1.
# 변환행렬 생성 (shiftX,Y가 양수일때 : 오른쪽, 아래로 이동)
M = np.float32([[1, 0, shiftX],[0, 1, shiftY]])
# cv2.warpAffine(입력이미지, 변환행렬, 출력이미지 크기)
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
2.
## 한줄로 이 함수 사용할 수도 있음
shifted = imutils.translate(image, shiftX, shiftY)
(5) 회전시키기(rotate)
1. OpenCV : 회전행렬 생성 + cv2. warfAffine 함수 사용하기
2. imutils : rotate / rotate_bound 함수 사용하기
* 회전각도가 양수일때 : 반시계방향(왼쪽)으로 회전
1.
# cv2.getRotationMatrix2D(center좌표, angle, scale)
M = cv2.getRotationMatrix2D((cX, cY), 45, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
2.
# imutils.rotate(입력이미지, angle)
rotated = imutils.rotate(image, 90)
# 이미지가 잘리지 않게 회전
rotated = imutils.rotate_bound(image, -33)
(6) Resize
# 150 pixel로 맞추기 위해 비율 구하기
r = 150.0 / image.shape[1]
dim = (150, int(image.shape[0] * r))
# cv2.resize(입력 이미지, 출력 이미지 크기, 보간법 방식)
cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
Interpolation 종류
이미지 축소 시 권장 cv2.INTER_NEAREST: 가장 빠르지만 품질 낮음 cv2.INTER_LINEAR: 기본값, 속도와 품질 균형 cv2.INTER_AREA: 이미지 축소에 권장 이미지 확대 시 권장 cv2.INTER_CUBIC: 품질 좋음, 속도 느림 cv2.INTER_LANCZOS4: 품질 매우 좋음, 가장 느림
# numpy로 image와 같은 크기에서 all 50의 값을 가지는 행렬 만들기
M = np.ones(image.shape, dtype="uint8") * 50
# OpenCV로 값 더해주기(밝아짐)
added = cv2.add(image, M)
# OpenCV로 값 빼주기(어두워짐)
subtracted = cv2.subract(image, M)
(10) Bitwise(and, or, xor, not)
rectangle = np.zeros((300, 300), dtype="uint8")
cv2.rectangle(rectangle, (25, 25), (275, 275), 255, -1)
circle = np.zeros((300, 300), dtype = "uint8")
cv2.circle(circle, (150, 150), 150, 255, -1)
bitwiseAnd = cv2.bitwise_and(rectangle, circle) # 둘 다 true인 부분 white
bitwiseOr = cv2.bitwise_or(rectangle, circle) # 둘 중 하나라도 true인 부분 white
bitwiseXor = cv2.bitwise_xor(rectangle, circle) # 둘 중 한쪽만 true인 부분 white
bitwiseNot = cv2.bitwise_not(rectangle, circle) # 둘 다 false인 부분 white