2024. 4. 16. 22:35ㆍCS/python 라이브러리
OpenCV는 오픈소스 컴퓨터비전 라이브러리로, python에서 이미지 혹은 영상처리를 할 때 유용하게 사용할 수 있다.
OpenCV 패키지 설치
먼저, OpenCV 패키지는 아래 명령어로 설치할 수 있다.
pip install opencv-python
OpenCV로 이미지 읽어오기
OpenCV의 cv2.imread() 함수를 이용해 이미지를 읽어올 수 있다. 이미지는 NumPy의 다차원 배열(numpy.ndarray) 객체로 저장되며, 이 배열은 이미지의 픽셀 값을 저장한다. 이미지 배열은 아래 요소를 갖는다.
- 색상: 이미지의 색상은 B, G, R 순으로 저장되며, 색상 채널은 0~255 사이의 값을 가진다.
- 형태: 이미지 배열은 (높이, 너비, 채널 수)로 표현되고, 흑백 이미지는 채널 수 없이 (높이, 너비)로만 표시된다.
- 타입: 일반적으로 픽셀의 색상은 uint8 (unsigned 8bit int)로 저장된다.
import cv2
img_path = 'my_image.jpg'
image = cv2.imread(img_path)
print(type(image)) #<class 'numpy.ndarray'>
if image is not None:
print("Shape of the image:", image.shape) #컬러 사진의 경우 (높이, 너비, 3)
print("Data type of the image:", image.dtype) #uint8
else:
print("Image not loaded.")
cv2.imread() 함수는 path 이외의 argument가 없으면 이미지를 컬러(BGR)로 읽어 온다. 여기에 아래와 같이 argument를 추가하면 흑백으로 읽을 수 있다.
img1 = cv2.imread(img_path, cv2.IMREAD_COLOR) #컬러로 읽음 (default)
img2 = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) #흑백으로 읽음
일반적으로 이미지 라이브러리는 BGR 순서보다 RGB 순서를 많이 사용하기에, 아래와 같이 cv2.cvtColor를 이용해 RGB로 순서를 변경해줄 수도 있다.
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
OpenCV로 이미지 변환하기
이미지 변환
크기 조정: cv2.resize()
img = cv2.imread('image.jpg')
resized_img = cv2.resize(img, (new_width, new_height))
회전: cv2.getRotationMatrix2D + cv2.warpAffine()
height, width = img.shape[:2]
center = (width / 2, height / 2)
matrix = cv2.getRotationMatrix2D(center, angle, scale)
rotated_img = cv2.warpAffine(img, matrix, (width, height))
이동: cv2.warpAffine()
img = cv2.imread('image.jpg')
tx, ty = 100, 50 # 이동할 픽셀 값
translation_matrix = np.float32([[1, 0, tx], [0, 1, ty]])
translated_img = cv2.warpAffine(img, translation_matrix, (img.shape[1], img.shape[0]))
플립: cv2.filp()
import cv2
img = cv2.imread('image.jpg')
flipped_img = cv2.flip(img, flipCode)
flipCode는 수직: 0, 수평: 1, 양축: -1을 사용한다.
영상처리
블러링: cv2.GaussianBlur(), cv2.medianBlur(), cv2.blur(), cv2.bilateralFilter()
에지 검출: cv2.Canny()
모폴로지 변환: cv2.erode(), cv2.dilate(), cv2.morphologyEx()
컨투어 찾기: cv2.findContours()
모양 분석: cv2.matchShapes()
노이즈 제거: cv2.fastNlMeansDenoising(), cv2.fastNlMeansDenoisingColored()
손상영역 복원: cv2.inpaint()
이외에도 얼굴 인식, 객체 감지, Optical Flow 등을 위한 다양한 메소드를 지원한다.
OpenCV로 이미지 저장하기/출력하기
OpenCV로 불러오고 변환한 이미지 객체는 cv2.imwrite() 함수를 통해 이미지 파일(jpg, png)로 변환할 수 있다.
cv2.imwrite(new_file_path, img)
이미지를 화면에 출력하기 위해서는 cv2.imshow() 함수를 사용한다.
cv2_imshow(img)
이미지를 여러 개 열고자 한다면, cv2.waitKey(0)로 사용자가 키를 누를 때까지 대기하도록 하는 방법도 있다.