Computer Vision Day 4

import cv2
import numpy as np
# GrayScale
src1 = cv2.imread('./data/lena.jpg', cv2.IMREAD_GRAYSCALE)
src2 = np.zeros(shape = src1.shape, dtype = np.uint8) + 50

# dst = src + 50 #모든 픽셀에 50씩 더해진다.
dst = cv2.add(src1, src2)

cv2.imshow('src1', src1)
cv2.imshow('dst', dst) # 검게 나온부분이 있는 이유는 255를 넘어갔기 때문
cv2.waitKey()
cv2.destroyAllWindows()
# Color
src1 = cv2.imread('./data/lena.jpg')
src2 = np.zeros(shape = src1.shape, dtype = np.uint8) + 50

# dst = src + 50 #모든 픽셀에 50씩 더해진다.
dst = cv2.add(src1, src2)

cv2.imshow('src', src1)
cv2.imshow('dst', dst) # 검게 나온부분이 있는 이유는 255를 넘어갔기 때문
cv2.waitKey()
cv2.destroyAllWindows()
  • 영상 연산(비트 연산)
lena = cv2.imread('./data/lena.jpg') 
logo = cv2.imread('./data/opencv_logo.png')
# cv2.imshow('lena', lena)
# cv2.imshow('logo', logo)
# cv2.waitKey()
# cv2.destroyAllWindows()

rows, cols, channel = logo.shape
roi = lena[:rows, :cols]

logo_gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
# cv2.imshow('logo_gray', logo_gray)
# cv2.waitKey()
# cv2.destroyAllWindows()

ret, mask = cv2.threshold(logo_gray, 160, 255, cv2.THRESH_BINARY)
# cv2.imshow('mask', mask)
# cv2.waitKey()
# cv2.destroyAllWindows()

mask_inv = cv2.bitwise_not(mask)
# cv2.imshow('mask_inv', mask_inv)
# cv2.waitKey()
# cv2.destroyAllWindows()

lena_bg = cv2.bitwise_and(roi, roi, mask = mask)
# cv2.imshow('lena_bg', lena_bg)
# cv2.waitKey()
# cv2.destroyAllWindows()

logo_fg = cv2.bitwise_and(logo, logo, mask=mask_inv)
# cv2.imshow('logo_fg', logo_fg)
# cv2.waitKey()
# cv2.destroyAllWindows()

dst = cv2.bitwise_or(lena_bg, logo_fg)
# cv2.imshow('dst', dst)
# cv2.waitKey()
# cv2.destroyAllWindows()

lena[:rows, :cols] = dst
cv2.imshow('lena', lena)
cv2.waitKey()
cv2.destroyAllWindows()
  • 실습(field.bmp 와 airplane.bmp 합성하기)
airplane = cv2.imread('./data/airplane.bmp') 
field = cv2.imread('./data/field.bmp')
# mask = cv2.imread('./data/mask_plane.bmp')
# mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)

airplane_gray = cv2.cvtColor(airplane, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(airplane_gray, 160, 255, cv2.THRESH_BINARY_INV)

mask_inv = cv2.bitwise_not(mask)

airplane_fg = cv2.bitwise_and(airplane, airplane, mask=mask)
field_bg = cv2.bitwise_and(field, field, mask = mask_inv)

dst = cv2.bitwise_or(airplane_fg, field_bg)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
  • 반전 영상
src1 = cv2.imread('./data/lena.jpg', cv2.IMREAD_GRAYSCALE)
src2 = np.zeros(shape=src1.shape, dtype=np.uint8) + 255
dst1 = 255 - src1
dst2 = cv2.subtract(src2, src1)
cv2.imshow('dst1', dst1)
cv2.imshow('dst2', dst2)
cv2.waitKey()
cv2.destroyAllWindows()
  • 명암비 정규화
src = cv2.imread('./data/lena.jpg', cv2.IMREAD_GRAYSCALE)

dst = cv2.normalize(src, None, 100, 200, cv2.NORM_MINMAX)

minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(src)

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

영상의 이진화

  • 전역 이진화
src = cv2.imread('./data/heart10.jpg', cv2.IMREAD_GRAYSCALE)

# ret, dst = cv2.threshold(src, 200, 255, cv2.THRESH_BINARY)

ret, dst = cv2.threshold(src, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
  • 적응형 이진화
src = cv2.imread('./data/srcThreshold.png', cv2.IMREAD_GRAYSCALE)

ret, dst = cv2.threshold(src, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

dst1 = cv2.adaptiveThreshold(src, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 51, 7)
dst2 = cv2.adaptiveThreshold(src, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 7)

cv2.imshow('src', src)
cv2.imshow('dst', dst)
cv2.imshow('dst1', dst1)
cv2.imshow('dst2', dst2)
cv2.waitKey()
cv2.destroyAllWindows()
  • 실습

selectROIs() 함수로 roi 2개를 입력 받아 각각 다른 효과 주기
1. 첫번째 roi는 그레이스케일로 변환후 150을 임계값으로 이진화
2. 두번째 roi는 반전

src = cv2.imread('./data/lena.jpg')
src_copy = cv2.imread('./data/lena.jpg')
rois = cv2.selectROIs('src_copy',src_copy)

for i, r in enumerate(rois):
    x,y,w,h = r
    roi = src_copy[y:y+h, x:x+w, :]

    if i == 0:
        gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
        ret, dst0 = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
        roi[:] = cv2.merge([dst0, dst0, dst0])
        
    elif i == 1:    
        roi[:] = 255-roi
    else:
        break   
        
cv2.imshow('src',src)    
cv2.imshow('src_copy',src_copy)
cv2.waitKey()
cv2.destroyAllWindows()     

히스토그램 분석

  • 히스토그램 분석
src = np.array([[0,0,0,0],
              [1,1,3,5],
              [6,1,1,3],
              [4,3,1,7]], dtype=np.uint8)
hist1 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[4], ranges=[0, 8])
hist1
array([[9.],
       [3.],
       [2.],
       [2.]], dtype=float32)
hist2 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[4], ranges=[0, 4])
hist2
array([[4.],
       [5.],
       [0.],
       [3.]], dtype=float32)
hist3 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[8], ranges=[0, 8])
hist3
array([[4.],
       [5.],
       [0.],
       [3.],
       [1.],
       [1.],
       [1.],
       [1.]], dtype=float32)
  • 히스토그램 분석 (lena 이미지)
src = cv2.imread('./data/lena.jpg', cv2.IMREAD_GRAYSCALE)
hist1 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[32], ranges=[0, 255])
hist1
array([[0.0000e+00],
       [0.0000e+00],
       [4.0000e+00],
       [4.6400e+02],
       [3.9770e+03],
       [1.2850e+04],
       [1.5358e+04],
       [9.7350e+03],
       [6.6210e+03],
       [6.9760e+03],
       [7.5430e+03],
       [9.9160e+03],
       [1.4930e+04],
       [1.2197e+04],
       [1.1506e+04],
       [1.5561e+04],
       [1.7768e+04],
       [1.7279e+04],
       [1.8438e+04],
       [2.0472e+04],
       [1.2959e+04],
       [9.8340e+03],
       [7.7420e+03],
       [5.4380e+03],
       [7.0620e+03],
       [7.3280e+03],
       [7.2620e+03],
       [2.4090e+03],
       [4.8200e+02],
       [2.9000e+01],
       [3.0000e+00],
       [1.0000e+00]], dtype=float32)
import matplotlib.pyplot as plt

hist1 = hist1.flatten()
plt.plot(hist1, color='r')

binX = np.arange(32)
plt.bar(binX, hist1, width=1, color='b')
<BarContainer object of 32 artists>

hist2 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[256], ranges=[0, 255])

hist2 = hist2.flatten()
plt.plot(hist2, color='r')

binX = np.arange(256)
plt.bar(binX, hist2, width=1, color='b')
<BarContainer object of 256 artists>

  • 채널별 히스토그램 분석 (lena 이미지)
src = cv2.imread('./data/lena.jpg')

Color = ['b','g','r']

for i in range(3):
    hist = cv2.calcHist(images=[src], channels=[i], mask=None, histSize=[256], ranges=[0, 255])
    plt.plot(hist, color=Color[i])

!

  • 히스토그램 스트래칭
src = cv2.imread('./data/hawkes.bmp', cv2.IMREAD_GRAYSCALE)

minVal, maxVal, minLoc, macLoc = cv2.minMaxLoc(src)

dst = ((src - minVal)/(maxVal - minVal)) * 255
dst = np.array(dst, dtype=np.uint8)

hist1 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[256], ranges = [0, 256])
hist2 = cv2.calcHist(images=[dst], channels=[0], mask=None, histSize=[256], ranges = [0, 256])

hist1 = hist1.flatten()
hist2 = hist2.flatten()

plt.title('src')
binX = np.arange(256)
plt.bar(binX, hist1, width=1, color='b')
plt.show()

plt.title('dst')
binX = np.arange(256)
plt.bar(binX, hist2, width=1, color='b')
plt.show()

cv2.imshow('src', src)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()     
  • 히스토그램 평활화
src = np.array([[0,0,0,0],
              [1,1,3,5],
              [6,1,1,3],
              [4,3,1,7]], dtype=np.uint8)

dst = cv2.equalizeHist(src)
dst
array([[  0,   0,   0,   0],
       [106, 106, 170, 212],
       [234, 106, 106, 170],
       [191, 170, 106, 255]], dtype=uint8)
  • 히스토그램 평활화(hawkes.bmp 이미지)
src = cv2.imread('./data/hawkes.bmp', cv2.IMREAD_GRAYSCALE)

dst = cv2.equalizeHist(src)

hist1 = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[256], ranges = [0, 256])
hist2 = cv2.calcHist(images=[dst], channels=[0], mask=None, histSize=[256], ranges = [0, 256])

hist1 = hist1.flatten()
hist2 = hist2.flatten()

plt.title('src')
binX = np.arange(256)
plt.bar(binX, hist1, width=1, color='b')
plt.show()

plt.title('dst')
binX = np.arange(256)
plt.bar(binX, hist2, width=1, color='b')
plt.show()

# cv2.imshow('dst',dst)
# cv2.waitKey()
# cv2.destroyAllWindows() 

  • 히스토그램 평활화 (pepper 컬러)
src = cv2.imread('./data/pepper.bmp')
dst1 = cv2.equalizeHist(src[:, :, 0])
dst2 = cv2.equalizeHist(src[:, :, 1])
dst3 = cv2.equalizeHist(src[:, :, 2])
dst = cv2.merge([dst1,dst2,dst3])
cv2.imshow('src', src)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
src = cv2.imread('./data/pepper.bmp')

yCrCb = cv2.cvtColor(src, cv2.COLOR_BGR2YCrCb)

y, Cr, Cb = cv2.split(yCrCb) #밝기, 레드, 블루

ye = cv2.equalizeHist(y)

dst = cv2.merge([ye, Cr, Cb])
dst2 = cv2.cvtColor(dst, cv2.COLOR_YCrCb2BGR)
cv2.imshow('src', src)
cv2.imshow('dst2', dst2)
cv2.waitKey()
cv2.destroyAllWindows()
  • 히스토그램 평활화 (lena)
src = cv2.imread('./data/lena.bmp')

yCrCb = cv2.cvtColor(src, cv2.COLOR_BGR2YCrCb)

y, Cr, Cb = cv2.split(yCrCb) #밝기, 레드, 블루

ye = cv2.equalizeHist(y)

dst = cv2.merge([ye, Cr, Cb])
dst2 = cv2.cvtColor(dst, cv2.COLOR_YCrCb2BGR)
cv2.imshow('src', src)
cv2.imshow('dst2', dst2)
cv2.waitKey()
cv2.destroyAllWindows()
src = cv2.imread('./data/lena.bmp')

hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)

h, s, v = cv2.split(hsv) #색상, 채도, 명도

ve = cv2.equalizeHist(v)

dst = cv2.merge([h, s, ve])
dst2 = cv2.cvtColor(dst, cv2.COLOR_HSV2BGR)
cv2.imshow('src', src)
cv2.imshow('dst2', dst2)
cv2.waitKey()
cv2.destroyAllWindows()
  • 히스토그램 역투영
src = np.array([[0,0,0,0],
              [1,1,3,5],
              [6,1,1,3],
              [4,3,1,7]], dtype=np.uint8)

hist = cv2.calcHist(images=[src], channels=[0], mask=None, histSize=[4], ranges=[0,8])
hist
array([[9.],
       [3.],
       [2.],
       [2.]], dtype=float32)
backP = cv2.calcBackProject([src], [0], hist, [0, 8], scale=1)
backP
array([[9, 9, 9, 9],
       [9, 9, 3, 2],
       [2, 9, 9, 3],
       [2, 3, 9, 2]], dtype=uint8)
src = cv2.imread('./data/fruits.jpg')

hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv) 

roi = cv2.selectROI(src)

roi_h = h[roi[1]:roi[1]+roi[3], roi[0]:roi[0]+roi[2]]

hist = cv2.calcHist([roi_h], [0], None, [64], [0, 256])
backP = cv2.calcBackProject([h.astype(np.float32)], [0], hist, [0, 256], scale=1) # 빈도수

hist = cv2.sort(hist, cv2.SORT_EVERY_COLUMN + cv2.SORT_DESCENDING)
T = hist[1][0] - 1

ret, dst = cv2.threshold(backP, T, 255, cv2.THRESH_BINARY)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
hist
array([[370.],
       [ 62.],
       [ 15.],
       [  1.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.],
       [  0.]], dtype=float32)

좋은 웹페이지 즐겨찾기