본문 바로가기

PyImageSearch

OpenCV : 기본함수들

PyImageSearch에서 학습중인 내용 정리 :)


(1) 이미지 가져오고 출력하기

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: 품질 매우 좋음, 가장 느림

 

(7) 이미지 뒤집기(Flipping)

# cv2.flip(원본이미지, flip code)
flipped = cv2.flip(image, 1)

 

Flip code
1 : flip horizontal(수평)
0 : flip vertical(수직)
-1 : flip horizontal & vertical
시계방향 순서대로 1.original ❘ 2. flip horizontal ❘ 3. flip horizontal & vertical ❘ 4. flip vertical

 

(8) 이미지 자르기(Cropping)

Numpy slicing 이해하기

 

 

# numpy clive 이용해서 이미지 자르기
sliced = image[85:220, 55:100]

cv2.imshow("sliced image", sliced)

 

(9) 이미지 보정(arithmetic)

행렬의 값을 더하고 빼는 형식이라 OpenCV와 Numpy 둘 다 사용 가능하지만,

Open CV 방식을 이용하는 것이 디버깅에 유리함. (Numpy는 어디서 에러가 났는지 찾기 거의 불가능)

# OpenCV
added = cv2.add(np.uint8([200]), np.uint8([100]))            >>> 255
subtracted = cv2.subtract(np.uint8([50]), np.uint8([100]))   >>> 0
# 결과의 최대치, 최소치가 255, 0 으로 제한됨

# numpy
added = np.uint8([200]) + np.uint8([100])         >>> 44  (300-255-1)            
subtracted = np.uint8([50]) - np.uint8([100])     >>> 206 (-50+255-1)
# 제한없고 255초과, 0미만 시 한 사이클을 돌아서 계속 실행됨
# 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

 

 

(11) Masking

mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.rectangle(mask, (0, 90), (290, 450), 255, -1)

# mask의 활성영역(rectangle)만 원본 픽셀값을 살리고 나머지는 0 처리됨
masked = cv2.bitwise_and(image, image, mask=mask)
plt_imshow("Mask Applied to Image", masked)

 

(12) Splitting and Merging channels

image = cv2.imread(args["image"])
# 이미지의 색깔별 3채널을 각각 분리
(B, G, R) = cv2.split(image)

plt_imshow("Red", R)
plt_imshow("Green", G)
plt_imshow("Blue", B)

 

# White = (255,255,255)  :  모든 채널에서 활성화(=white)
# Red = (0,0,255) : G,B 채널에서는 비활성화(0,black),  Red 채널에서는 활성화(255,white)

 

* Red channel에서는 빨간색만 남을 것 같지만 오히려 반대다!!

# show each channel individually

zeros = np.zeros(image.shape[:2], dtype="uint8")

plt_imshow("Red", cv2.merge([zeros, zeros, R]))
plt_imshow("Green", cv2.merge([zeros, G, zeros]))
plt_imshow("Blue", cv2.merge([B, zeros, zeros]))

 

# Red : Red층에서 흰색 & 빨간색인 부분은(0,0,255)니까 “빨강 성분만 남고, 파랑·초록 성분은 모두 검게 꺼진” 형태가 남음

 


출처

https://www.pyimagesearch.com/2021/01/20/opencv-load-image-cv2-imread/?_ga=2.110844485.1773329974.1749613563-254784589.1749433426

 

OpenCV Load Image (cv2.imread) - PyImageSearch

In this tutorial, you will learn how to use OpenCV and the cv2.imread function to load an input image from disk, determine the image’s width, height, and number of channels, display the loaded image to our screen, and write the image back out to disk as

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/20/opencv-getting-and-setting-pixels/?_ga=2.110844485.1773329974.1749613563-254784589.1749433426

 

OpenCV Getting and Setting Pixels - PyImageSearch

In this tutorial, you will learn how to get and set pixel values using OpenCV and Python.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/27/drawing-with-opencv/?_ga=2.89888091.1773329974.1749613563-254784589.1749433426

 

Drawing with OpenCV - PyImageSearch

In this tutorial, you will learn how to use OpenCV’s basic drawing functions. You will learn how to use OpenCV to draw lines, rectangles, and circles.

pyimagesearch.com

https://www.pyimagesearch.com/2021/02/03/opencv-image-translation/?_ga=2.89888091.1773329974.1749613563-254784589.1749433426

 

OpenCV Image Translation - PyImageSearch

In this tutorial, you will learn how to translate and shift images using OpenCV.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/20/opencv-rotate-image/?_ga=2.89888091.1773329974.1749613563-254784589.1749433426

 

OpenCV Rotate Image - PyImageSearch

In this tutorial, you will learn how to rotate an image using OpenCV. Additionally, I’ll also show you how to rotate an image using my two convenience functions from the imutils library, imutils.rotate and imutils.rotate_bound, which make rotating images

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/20/opencv-resize-image-cv2-resize/?_ga=2.89888091.1773329974.1749613563-254784589.1749433426

 

OpenCV CV2 Resize Image ( cv2.resize ) - PyImageSearch

In this tutorial, you will learn how to resize an image using OpenCV and the cv2.resize function.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/20/opencv-flip-image-cv2-flip/?_ga=2.89888091.1773329974.1749613563-254784589.1749433426

 

OpenCV Flip Image ( cv2.flip ) - PyImageSearch

In this tutorial, you will learn how to flip images using OpenCV and the cv2.flip function.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/19/crop-image-with-opencv/?_ga=2.89888091.1773329974.1749613563-254784589.1749433426

 

Crop Image with OpenCV - PyImageSearch

In this tutorial, you will learn how to crop images using OpenCV.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/19/image-arithmetic-opencv/?_ga=2.88355291.1773329974.1749613563-254784589.1749433426

 

Image Arithmetic OpenCV - PyImageSearch

In this tutorial, you will learn how to perform image arithmetic (addition and subtraction) with OpenCV.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/19/opencv-bitwise-and-or-xor-and-not/?_ga=2.88355291.1773329974.1749613563-254784589.1749433426

 

OpenCV Bitwise AND, OR, XOR, and NOT - PyImageSearch

In this tutorial, you will learn how to apply bitwise AND, OR, XOR, and NOT with OpenCV.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/19/image-masking-with-opencv/?_ga=2.88355291.1773329974.1749613563-254784589.1749433426

 

Image Masking with OpenCV - PyImageSearch

In this tutorial, you will learn how to mask images using OpenCV.

pyimagesearch.com

https://www.pyimagesearch.com/2021/01/23/splitting-and-merging-channels-with-opencv/?_ga=2.88355291.1773329974.1749613563-254784589.1749433426

 

Splitting and Merging Channels with OpenCV - PyImageSearch

In this tutorial, you will learn how to split and merge channels with OpenCV.

pyimagesearch.com

 

 

'PyImageSearch' 카테고리의 다른 글

OpenCV - Thresholding(이진화)  (0) 2025.06.12
OpenCV - Color Spaces  (0) 2025.06.12
OpenCV - 블러처리  (2) 2025.06.12
OpenCV - Morphological Operations(형태학적 연산)  (0) 2025.06.11
CommandLine Arguments  (2) 2025.06.03