Computer Vision Day 1

import cv2
cv2.__version__
'4.5.3'

실습 1.영상 파일 읽기 및 화면 표시

imgFile = './data/lena.jpg'

img = cv2.imread(imgFile) # cv2.IMREAD_COLOR
img2 = cv2.imread(imgFile, 0) # cv2.IMREAD_GRAYSCALE

cv2.imshow("Lena Color", img)
cv2.imshow("Lena GrayScale", img2)

cv2.waitKey()
cv2.destroyAllWindows()

실습 2.영상 파일 저장

imgFile = './data/lena.jpg'

img = cv2.imread(imgFile) # cv2.IMREAD_COLOR

cv2.imwrite('./Lena.bmp' ,img)
cv2.imwrite('./Lena.png' ,img)
cv2.imwrite('./Lena_compression.png' ,img, [cv2.IMWRITE_PNG_COMPRESSION, 9])
cv2.imwrite('./Lena_compression.jpg' ,img, [cv2.IMWRITE_JPEG_QUALITY, 90])
True

실습 3. matplotlib 컬러영상 표기

import matplotlib.pyplot as plt
imgFile = './data/lena.jpg'
img = cv2.imread(imgFile) # cv2.IMREAD_COLOR

plt.imshow(img)
plt.show()

img.shape
(512, 512, 3)
import numpy as np

imgRGB = np.zeros((512,512,3), dtype='uint8')
imgRGB[:,:,2] = img[:, :, 0] # blue
imgRGB[:,:,1] = img[:, :, 1] # green
imgRGB[:,:,0] = img[:, :, 2] # red
plt.imshow(imgRGB)
plt.show()

imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(imgRGB)
plt.show()

실습 4. matplotlib 2 : 그레이 스케일 영상 표기

imgFile = './data/lena.jpg'
imgGray = cv2.imread(imgFile, cv2.IMREAD_GRAYSCALE) # cv2.IMREAD_GRAYSCALE

plt.axis("off")
plt.imshow(imgGray, cmap="gray", interpolation = 'bicubic')
plt.show()

실습 6. matplotilb 4: 서브플롯에 영상 표시

imgBGR1 = cv2.imread('./data/lena.jpg')
imgBGR2 = cv2.imread('./data/apple.jpg')
imgBGR3 = cv2.imread('./data/baboon.jpg')
imgBGR4 = cv2.imread('./data/orange.jpg')
imgRGB1 = cv2.cvtColor(imgBGR1, cv2.COLOR_BGR2RGB)
imgRGB2 = cv2.cvtColor(imgBGR2, cv2.COLOR_BGR2RGB)
imgRGB3 = cv2.cvtColor(imgBGR3, cv2.COLOR_BGR2RGB)
imgRGB4 = cv2.cvtColor(imgBGR4, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(2, 2, figsize = (10,10), sharey=True)

ax[0][0].axis("off")
ax[0][0].imshow(imgRGB1, aspect='auto')

ax[0][1].axis("off")
ax[0][1].imshow(imgRGB2, aspect='auto')

ax[1][0].axis("off")
ax[1][0].imshow(imgRGB3, aspect='auto')

ax[1][1].axis("off")
ax[1][1].imshow(imgRGB4, aspect='auto')

plt.subplots_adjust(left=0, bottom=0, right=1, top=1, 
                     wspace=0.05, hspace=0.05)

plt.savefig("./4images.png")
plt.show()

cap = cv2.VideoCapture(0)
frame_size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

while True:
    retval, frame = cap.read() # 프레임 캡처
    if not retval:
        break
        
    cv2.imshow("frame", frame)    
    
    key = cv2.waitKey(25)
    if key == 27:
        break
        
if cap.isOpened():
    cap.release()
    
cv2.destroyAllWindows()    

좋은 웹페이지 즐겨찾기