Opencv

7-3-1 Opencv 3.3의 기초 사용법-I

coding art 2019. 12. 20. 13:19
728x90

Opencv를 설치했으면 간단한 이미지 처리 사용법을 알아보자. Opencv 설치과정에서 numpy 와 함께 이미 PiCamera imutils 를 함께 설치해 두었다는 사실을 기억하자.

pip install numpy

pip install picamera[array]

pip install imutils

 

파이카메라는 라즈베리파이 홈페이지에서 파이카메라 사용법을 친절하게 설명해 주고 있다. 한편 Adrian의 아래 블로그에 따라 기초적인 사용법을 살펴보기로 한다. 라즈베리파이에 관한한 Adrian 의 블로그 내용이 고퀄리티임은 부인할 수 없는 사실이다.

OpenCV Tutorial: A Guide to Learn OpenCV

https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/

 

항상 Adrian 블로그의 하단에 Downloads에 이메일을 타이프하여 보내면 예제코드를 다운로드 시켜준다는 사실에 유의하자. 다운로드 받은 zip을 푼 후 터미널에서 tree 명령으로 살펴보면 쥬라기파크(jurassic park, jp) 사진 한 장과 _01, _02 파이썬 파일들과 테트리스 그림 png 파일이 들어 있음을 알 수 있다.

 

opencv_tutorial_01.py Python 3(IDLE) 로 불러내어 실행시켜 보자. 지난번에 Opencv

가상환경에 설치했지만 아직은 가상환경을 사용함이 없이 그냥 실행 시켜 보자.

필요한 라이브러리들을 import 하자.하나는 imutils 이고 다른 하나는 cv2 이다. imutils 는 이미지 파일과 앞으로도 다루게 될 비데오 스트림 파일을 처리해 줄 수 있는 편의용 즉 유틸리티용 라이브러리이다. cv2 가 바로 opencv 라이브러리 모듈을 지칭하는데 숫자 2opencv 의 버전 2, 3.3.0, 4.0을 의미하는 것은 아니며 관행으로 그렇게 사용한다.

 

파이썬 코드가 이어서 실행해야 할 첫 번째 명령은 이미지 파일을 읽어 들이는 과정이다. 다른 이미지 그래픽 라이브러리 matplotlib 에서와 마찬가지로image read imread 명령을 사용한다. image.shape 명령에서 shapeTensorFlow 머신러닝에서 많이 사용되는 명령으로 이미지 데이터의 매트릭스 구조를 간단히 나타낸다. 명령의 앞부분에 클래스 명령인 cv2. 이 없는 경우는 파이썬 명령으로 분류되며 cv2. 이 붙어 있으면 Opencv 명령에 해당한다.

 

여기서는 h는 이미지 파일의 높이 방향 픽셀 수이며, w는 폭 방향 픽셀 수이고, d는 픽셀의 B,G,R 컬러를 뜻하며 값이 3이 된다.

 

 

불러들인 이미지 파일을 화면에 디스플레이 하기 위해서 imshow 명령을 사용하자. waitkey(0) 명령은 코드가 키보드 입력을 대기하게끔 하는 명령이다. 15번 라인을 넘어가기 위해서는 imshow 로 디스플레이 된 image 파일을 한번 클릭한 후에 키보드 0을 입력하면 그 다음 명령으로 진행이 이루어진다. 대단히 중요한 파이썬 용법이다.

 

 

RGB 라고 흔히 사용하지만 Opencv 에서는 BGR 로 표현한다. RGB 표현이 사용되기 훨씬 전에 BGR 이 사용되던 시기에 이미 Opencv 가 개발되었기 때문에 관행으로 굳었음에 유의하자. Gray scale 에서는 0 이 검정색이며 255가 가장 밝은 흰색이 된다.

 

 

쥬라기 파크 사진의 높이 좌표값이 100, 폭 좌표 값이 50인 지점의 B, G, R 값을 다음과 같이 출력해 볼 수 있다.

 

 

Opencv 뿐만 아니라 모든 이미지 처리 과정에서 중요한 작업 중의 하나가 ROI(Region of Interest) 즉 관심영역을 도려내는 작업으로서 불필요한 그래픽 이미지 정보를 제거하는 측면도 있지만 한편 도려낸 그래픽 이미지의 크기들을 이미지 처리 코드에 적합한 크기로 사전 조절하는 작업으로서 Crop 이라고도 한다.

 

 

다음 프로그램의 image[60:160, 320:420]에서 높이 기준 600에 대한 60:160, 폭 기준 400에 대한 320:420 부분을 잘라내는 작업을 뜻한다.

 

 

주어진 이미지 파일 전체의 크기를 조절하는 Resize에 대해서 알아보자. 다음 사례는 600:400 이미지를 200:200 으로 Resize 한 경우다. Resize(a, b)에서 a 는 폭이고 b 는 높이가 된다.

 

 

다음 사례는 폭과 높이 비율을 일정하게 유지하는 Resize 사례이다.

 

 

한편 Opencv 에서도 Resize 명령이 있지만 가상환경에 설치했던 라이브러리 모듈인 imutils 에서도 다음과 같이 Resize 명령을 제공한다. 만약 현재의 코드를 가상환경에 들어가지 않은 상태에서 실행하면 이 부분의 이미지 처리 결과를 볼 수 없을 것이다.

반면에 다음과 같이 가상환경 cv 에 들어가도록 한 후

source ~/.profile

workon cv

 

현재의 코드를 실행하면 그 결과를 볼 수 있을 것이다.

 

 

7-3-2 Opencv 3.3의 기초적인 사용법-II 에서 계속

 

이미지 파일 jp.png

 

다운로드해서 사용하자.

jp.png
0.28MB

 

# python opencv_tutorial_01.py

# USAGE

# import the necessary packages

import imutils

import cv2

 

# load the input image and show its dimensions, keeping in mind that

# images are represented as a multi-dimensional NumPy array with

# shape no. rows (height) x no. columns (width) x no. channels (depth)

image = cv2.imread("jp.png")

(h, w, d) = image.shape

print("width={}, height={}, depth={}".format(w, h, d))

 

# display the image to our screen -- we will need to click the window

# open by OpenCV and press a key on our keyboard to continue execution

cv2.imshow("Image", image)

cv2.waitKey(0)

 

# access the RGB pixel located at x=50, y=100, keepind in mind that

# OpenCV stores images in BGR order rather than RGB

(B, G, R) = image[100, 50]

print("R={}, G={}, B={}".format(R, G, B))

 

# extract a 100x100 pixel square ROI (Region of Interest) from the

# input image starting at x=320,y=60 at ending at x=420,y=160

roi = image[60:160, 320:420]

cv2.imshow("ROI", roi)

cv2.waitKey(0)

 

# resize the image to 200x200px, ignoring aspect ratio

resized = cv2.resize(image, (200, 200))

cv2.imshow("Fixed Resizing", resized)

cv2.waitKey(0)

 

# fixed resizing and distort aspect ratio so let's resize the width

# to be 300px but compute the new height based on the aspect ratio

r = 300.0 / w

dim = (300, int(h * r))

resized = cv2.resize(image, dim)

cv2.imshow("Aspect Ratio Resize", resized)

cv2.waitKey(0)

 

# manually computing the aspect ratio can be a pain so let's use the

# imutils library instead

resized = imutils.resize(image, width=300)

cv2.imshow("Imutils Resize", resized)

cv2.waitKey(0)

 

# let's rotate an image 45 degrees clockwise using OpenCV by first

# computing the image center, then constructing the rotation matrix,

# and then finally applying the affine warp

center = (w // 2, h // 2)

M = cv2.getRotationMatrix2D(center, -45, 1.0)

rotated = cv2.warpAffine(image, M, (w, h))

cv2.imshow("OpenCV Rotation", rotated)

cv2.waitKey(0)

 

# rotation can also be easily accomplished via imutils with less code

rotated = imutils.rotate(image, -45)

cv2.imshow("Imutils Rotation", rotated)

cv2.waitKey(0)

 

# OpenCV doesn't "care" if our rotated image is clipped after rotation

# so we can instead use another imutils convenience function to help

# us out

rotated = imutils.rotate_bound(image, 45)

cv2.imshow("Imutils Bound Rotation", rotated)

cv2.waitKey(0)

 

# apply a Gaussian blur with a 11x11 kernel to the image to smooth it,

# useful when reducing high frequency noise

blurred = cv2.GaussianBlur(image, (11, 11), 0)

cv2.imshow("Blurred", blurred)

cv2.waitKey(0)

 

# draw a 2px thick red rectangle surrounding the face

output = image.copy()

cv2.rectangle(output, (320, 60), (420, 160), (0, 0, 255), 2)

cv2.imshow("Rectangle", output)

cv2.waitKey(0)

 

# draw a blue 20px (filled in) circle on the image centered at

# x=300,y=150

output = image.copy()

cv2.circle(output, (300, 150), 20, (255, 0, 0), -1)

cv2.imshow("Circle", output)

cv2.waitKey(0)

 

# draw a 5px thick red line from x=60,y=20 to x=400,y=200

output = image.copy()

cv2.line(output, (60, 20), (400, 200), (0, 0, 255), 5)

cv2.imshow("Line", output)

cv2.waitKey(0)

 

# draw green text on the image

output = image.copy()

cv2.putText(output, "OpenCV + Jurassic Park!!!", (10, 25), 

cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

cv2.imshow("Text", output)

cv2.waitKey(0)