[OpenCV] 이미지 연산 실습

heegon·2026년 3월 31일

컴퓨터비전

목록 보기
2/3

이미지 업로드 및 이미지 정보 확인하기

cv2.imread() -> 이미지를 디스크에서 읽어들여 OpenCV의 NumPy 배열 형태로 로드한다.

image.shape

image.shape[0] -> Height
image.shape[1] -> Width
image.shape[2] -> Channels

image.size -> 전체 픽셀 수(Height x Width x Channels)를 의미한다.

image[y, x] -> (y,x) 위치의 픽셀(BGR) 정보를 배열 형태로 얻는다.
=> image[Height, Width]

OpenCV에서는 BGR (Blue, Green, Red) 순서가 기본이다. (보통은 RGB)

image[y, x][0] => Blue
image[y, x][1] => Green
image[y, x][2] => Red

코드로 공부하기

# Colab에 이미지 업로드
uploaded = files.upload()

# 업로드된 첫 번째 이미지 파일 이름 가져오기
filename = list(uploaded.keys())[0]

# 이미지를 BGR 컬러로 읽기
image = cv2.imread(filename, cv2.IMREAD_COLOR)

# 이미지 기본 정보 확인하기
print("이미지 크기 확인 (Height, Width, Channels) : ", image.shape)
print("이미지 전체 픽셀 수 : ", image.size)

# 특정 픽셀의 BGR 값 확인
# (100,100) 위치로 가정
y, x = 100, 100 

if y < image.shape[0] and x < image.shape[1]:
	px = image[y, x]
    print(f"({y},{x}) 위치 픽셀의 BGR 값 : ", px)
    print(f"({y},{x}) 위치 픽셀의 Blue 값 : ", px[0])
    print(f"({y},{x}) 위치 픽셀의 Green 값 : ", px[1])
    print(f"({y},{x}) 위치 픽셀의 Red 값 : ", px[2])    
else:
	print(f"이미지 크기가 작아서, {y},{x} 픽셀이 존재하지 않습니다.")

특정 범위 픽셀 변경하기

슬라이싱 방식

# 이미지 복사본 생성
image_copy = image.copy()

start_time = time.time()
rows = min(100, image_copy.shape[0])
cols = min(100, image_copy.shape[1])

# 슬라이싱을 이용한 특정 범위 변경
image_copy2 = image.copy()
start_time = time.time()
image_copy2[0:rows, 0:cols] = [255,255,255] # 검정색으로 변경
end_time = time.time()
print("%.6f seconds" %(end_time - start_time))

# 결과 이미지 보기
cv2_imshow(image_copy2)

ROI (Region of Interest) 추출 및 복사

ROI 추출

# ROI 추출 예시
image_copy3 = image.copy()

# 안전하게 min() 함수를 사용하여 이미지 범위 내에서만 추출
roi = image_copy3[20:min(150, image_copy3.shape[0]), 70:min(200, image_copy3.shape[1])]

# 잘라낸 ROI 확인
cv2_imshow(roi)

ROI 복사 후 다른 곳에 붙여넣기

# ROI를 다른 위치에 복사

# 이미지의 높이 정보를 가져와서 h_roi에 저장하고, 너비 정보를 w_roi 에 저장
h_roi, w_roi = roi.shape[:2]

# 이미지 끝 지점 지정
end_y = min(h_roi, image_copy3.shape[0])
end_x = min(w_roi, image_copy3.shape[1])

# 0부터 end_y까지, 0부터 end_x 까지를 roi 로 변경
image_copy3[0:end_y, 0:end_x] = roi

cv2_imshow(image_copy3)
profile
❤️

0개의 댓글