OpenCV-Python (3) 영상의 속성과 픽셀 값 참조

hjwon·2023년 9월 3일
0

OpenCV-Python

목록 보기
3/6

📌 OpenCV는 영상 데이터를 numpy.ndarray로 표현

  • ndim: 차원 수, len(img.shape)과 같음

  • shape: 각 차원의 크기
    (h, w) - 그레이스케일 영상(2차원)
    (h, w, 3) - 컬러 영상(3차원)

  • size: 전체 원소 개수

  • dtype: 원소의 데이터 타입, 영상 데이터는 uint8


📌 OpenCV 영상 데이터 자료형과 Numpy 자료형

OpenCV 자료형 (1채널)Numpy 자료형구분
cv2.CV_8Unumpy.uint88비트 부호 없는 정수
cv2.CV_8Snumpy.int88비트 부호 있는 정수
cv2.CV_16Unumpy.uint1616비트 부호 없는 정수
cv2.CV_16Snumpy.int1616비트 부호 있는 정수
cv2.CV_32Snumpy.int3232비트 부호 있는 정수
cv2.CV_32Fnumpy.float3232비트 부동소수형
cv2.CV_64Fnumpy.float6464비트 부동소수형
cv2.CV_16Fnumpy.float1616비트 부동소수형
  • 그레이스케일 영상: cv2.CV_8UC1 → numpy.uint8, shape = (h, w)
  • 컬러 영상: cv2.CV_8UC3 → numpy.uint8, shape = (h, w, 3)


💻 영상의 속성 참조 예제

img1 = cv2.imread('cat.bmp', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('cat.bmp', cv2.IMREAD_COLOR)

print('type(img1):', type(img1))   # type(img1): <class 'numpy.ndarray'>
print('img1.shape:', img1.shape)   # img1.shape: (480, 640)
print('img2.shape:', img2.shape)   # img2.shape: (480, 640, 3)
print('img2.dtype:', img2.dtype)   # img2.dtype: uint8

h, w = img2.shape[:2]   # h: 480, w: 640
print('img2 size: {} X {}'.format(w, h))   # img2 size: 640 X 480

if len(img1.shape) == 2:
	print('img1 is a grayscale image')
elif len(img1.shape) == 3:
	print('img1 is a truecolor image')



💻 영상의 픽셀 값 참조 예제

img1 = cv2.imread('cat.bmp', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('cat.bmp', cv2.IMREAD_COLOR)

# for문으로 픽셀 값을 변경하는 작업은 매우 느리므로,
# 픽셀 값 참조 방법만 확인하고 실제로는 사용 금지
for y in range(h):
	for x in range(w):
    	img1[y, x] = 255   # img1 픽셀 값 흰색으로 변경
        img2[y, x] = (0, 255, 255)   # img2 픽셀 값 노란색으로 변경
        
#img1[:,:] = 255
#img2[:,:] = (0, 255, 255)



profile
열공워니

0개의 댓글