728x90
import cv2 as cv
import os
import numpy as np

dt_path = os.path.join(os.path.expanduser('~'),'Desktop')
os.chdir(dt_path)


img_color = cv.imread("test.jpg", cv.IMREAD_COLOR)

# 이미지의 높이와 너비를 가져옵니다.
height, width = img_color.shape[:2]
print(img_color.shape)
# gray scale image 를 저장할 numpy array 를 생성합니다.
img_gray = np.zeros((height, width), np.uint8)

# for 문을 돌면서 (x, y)에 있는 픽셀을 하나씩 접근합니다.
for y in range(0, height):
	for x in range(0, width):
		# color image 의 (x, y)에 있는 픽셀의 b, g, r채널을 읽습니다.
		b = img_color.item(y, x, 0)
		g = img_color.item(y, x, 1)
		r = img_color.item(y, x, 2)

		# (x, y)위치의 픽셀에 gray scale 값이 저장됩니다.
		# 평균값 사용하는 경우
		#gray = int((r + g + b) / 3.0)
		#BT.709에 명시된 비율을 사용하는 경우
		gray = int(r*0.2126 + g*0.7152 + b*0.0722)

		img_gray.itemset(y, x, gray)

# 결과 이미지에 컬러를 표시하기 위해
# 컬러 이미지로 변환합니다.
img_result = cv.cvtColor(img_gray, cv.COLOR_GRAY2BGR)

# 범위가 150~200, x범위가 200~250인 영역의 픽셀을
# 초록색 픽셀로 변경합니다.
for y in range(150, 201):
	for x in range(200, 251):
		img_result.itemset(y, x, 0, 0)
		img_result.itemset(y, x, 1, 255)
		img_result.itemset(y, x, 2, 0)

cv.imshow('color', img_color)
cv.imshow('result', img_result)

cv.waitKey(0)
cv.destroyWindow()

 

바탕화면을 현재 작업 경로로 지정하기 위해서 chdir함수를 사용했습니다.

 

 

728x90