AI/컴퓨터 비전

[Python, OpenCV 4로 배우는 컴퓨터 비전과 머신러닝] CH03

HHB 2022. 12. 4. 01:23

func1 : 이미지를 회색조 이미지로 불러오고 화면에 띄우기 까지

import numpy as np
import cv2

def func1():
    img1 = cv2.imread('cat.bmp', cv2.IMREAD_GRAYSCALE)

    if img1 is None:
        print('Image load failed!')
        return

    print('type(img1):', type(img1))
    print('img1.shape:', img1.shape)

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

    cv2.imshow('img1', img1)
    cv2.waitKey()
    cv2.destroyAllWindows()

 

 

func2 : 넘파이로 이미지 생성하기

def func2():
    img1 = np.empty((480, 640), np.uint8)       # grayscale image
    img2 = np.zeros((480, 640, 3), np.uint8)    # color image
    img3 = np.ones((480, 640), np.uint8) * 124        # 1's matrix
    img4 = np.full((480, 640, 3), (0, 125, 125), np.uint8)   # Fill with 0.0

    mat1 = np.array([[11, 12, 13, 14],
                     [21, 22, 23, 24],
                     [31, 32, 33, 34]]).astype(np.uint8)

    mat1[0, 1] = 100    # element at x=1, y=0
    mat1[2, :] = 200
    
    cv2.imshow('img1', img1)
    cv2.imshow('img2', img2)
    cv2.imshow('img3', img3)
    cv2.imshow('img4', img4)

    cv2.waitKey()
    cv2.destroyAllWindows()
    print(mat1)

 

func3 : 영상 완전 복사, 참조

def func3():
    img1 = cv2.imread('cat.bmp')

    img2 = img1
    img3 = img1.copy()

    img1[:, :] = (0, 255, 255)  # yellow

    cv2.imshow('img1', img1)
    cv2.imshow('img2', img2)
    cv2.imshow('img3', img3)
    cv2.waitKey()
    cv2.destroyAllWindows()

img2는 img1의 주소를 참조하기 있어 img1이 변경되면 같이 변경된다.

img3는 .copy() 를 통해 값 자체를 복사해 할당하기 때문에 img1가 변경되고 변하지 않는다.

func4 : 이미지 슬라이싱,  완전 복사, 참조

def func4():
    img1 = cv2.imread('lenna.bmp', cv2.IMREAD_GRAYSCALE)

    img2 = img1[200:400, 200:400]
    img3 = img1[200:400, 200:400].copy()

    img2 += 100

    cv2.imshow('img1', img1)
    cv2.imshow('img2', img2)
    cv2.imshow('img3', img3)
    cv2.waitKey()
    cv2.destroyAllWindows()

img2는 img1의 일정 부분만 참조한다. 이미지 크기는 200, 200

img3는 img2처럼 일정 부분만 가져오나 copy로 완전 복사 한다.

img2에 +100을 해줌으로써 img2, img2에 해당되는 img1에도 +100이 되어 이미지가 변경된다.

 

728x90
반응형
LIST