생능출판사 (가칭)"데이터과학 파이썬" 코드 13장

13.2 맷플롯립으로 간단히 이미지 그려보기

In [1]:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('d:/data/mandrill.png')
print(img)
[[[0.45882353 0.41960785 0.21960784]
  [0.26666668 0.22352941 0.14509805]
  [0.42352942 0.36078432 0.20784314]
  ...
  [0.36862746 0.36078432 0.22745098]
  [0.5254902  0.50980395 0.33333334]
  [0.56078434 0.60784316 0.40784314]]

 [[0.42352942 0.36078432 0.20784314]
  [0.32941177 0.3019608  0.1764706 ]
  [0.32941177 0.3019608  0.1764706 ]
  ...
  [0.4117647  0.5019608  0.34901962]
  [0.36862746 0.35686275 0.29411766]
  [0.27450982 0.30588236 0.21176471]]

 [[0.45882353 0.41960785 0.21960784]
  [0.45882353 0.41960785 0.21960784]
  [0.32941177 0.3019608  0.1764706 ]
  ...
  [0.37254903 0.40392157 0.24313726]
  [0.28235295 0.27450982 0.1764706 ]
  [0.47058824 0.5372549  0.3529412 ]]

 ...

 [[0.3647059  0.46666667 0.4117647 ]
  [0.44705883 0.5803922  0.6117647 ]
  [0.52156866 0.5686275  0.6039216 ]
  ...
  [0.36078432 0.41960785 0.34509805]
  [0.39215687 0.36078432 0.36078432]
  [0.32941177 0.32156864 0.28627452]]

 [[0.44705883 0.5803922  0.6117647 ]
  [0.5254902  0.61960787 0.61960787]
  [0.46666667 0.57254905 0.5372549 ]
  ...
  [0.39215687 0.36078432 0.36078432]
  [0.39215687 0.36078432 0.36078432]
  [0.36862746 0.35686275 0.29411766]]

 [[0.28627452 0.35686275 0.34117648]
  [0.23921569 0.28627452 0.2784314 ]
  [0.23529412 0.27450982 0.22745098]
  ...
  [0.18431373 0.18039216 0.14117648]
  [0.18431373 0.18039216 0.14117648]
  [0.16470589 0.14901961 0.17254902]]]
In [2]:
img_plot = plt.imshow(img)
plt.show()

13.3 좀 더 편리한 이미지 도구는 없을까

In [3]:
!pip install opencv-python
Requirement already satisfied: opencv-python in c:\users\shjung\anaconda3\lib\site-packages (4.5.5.64)
Requirement already satisfied: numpy>=1.14.5; python_version >= "3.7" in c:\users\shjung\anaconda3\lib\site-packages (from opencv-python) (1.21.5)
In [4]:
import cv2


img_gray = cv2.imread('d:/data/mandrill.png', cv2.IMREAD_GRAYSCALE)
img_color = cv2.imread('d:/data/mandrill.png', cv2.IMREAD_COLOR)

cv2.imshow('grayscale', img_gray)
cv2.imshow('color image', img_color)

cv2.waitKey(0)
cv2.destroyAllWindows()

13.4 OpenCV로 이미지 다루어 보자

In [5]:
import cv2
img = cv2.imread('d:/data/mandrill.png', 1)
cv2.line(img, (0,0), (200,200), (0,0,255), 5)
cv2.arrowedLine(img, (0,200), (200,20), (0,0,255), 5)
cv2.imshow('lined', img)
cv2.waitKey(0)
Out[5]:
-1
In [6]:
cv2.rectangle(img, (0,200), (200,20), (0,0,0), 5)
cv2.putText(img, "hello", (70,70), fontFace = 2, fontScale = 1, color = (0,0,0))
Out[6]:
array([[[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        ...,
        [ 58,  92,  94],
        [ 85, 130, 134],
        [104, 155, 143]],

       [[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        ...,
        [ 89, 128, 105],
        [ 75,  91,  94],
        [ 54,  78,  70]],

       [[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        ...,
        [ 62, 103,  95],
        [ 45,  70,  72],
        [ 90, 137, 120]],

       ...,

       [[105, 119,  93],
        [156, 148, 114],
        [154, 145, 133],
        ...,
        [ 88, 107,  92],
        [ 92,  92, 100],
        [ 73,  82,  84]],

       [[156, 148, 114],
        [158, 158, 134],
        [137, 146, 119],
        ...,
        [ 92,  92, 100],
        [ 92,  92, 100],
        [ 75,  91,  94]],

       [[ 87,  91,  73],
        [ 71,  73,  61],
        [ 58,  70,  60],
        ...,
        [ 36,  46,  47],
        [ 36,  46,  47],
        [ 44,  38,  42]]], dtype=uint8)

13.5 합성 사진을 제작해 보자

In [7]:
import cv2
global img1, img2

def on_change_weight(x):
    weight = x / 100
    img_merged = cv2.addWeighted(img1, 1-weight, img2, weight, 0)
    cv2.imshow('Display', img_merged)

cv2.namedWindow('Display')
cv2.createTrackbar('weight', 'Display', 0, 100, on_change_weight)

img1 = cv2.imread('d:/data/green_back.png')
img2 = cv2.imread('d:/data/iceberg.jpg')
img1 = cv2.resize(img1, (300,400))
img2 = cv2.resize(img2, (300,400))

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

13.6 이미지에 마스크를 씌워볼까

In [8]:
import cv2
mask_image = cv2.imread('d:/data/mask_python.png')
back_image = cv2.imread('d:/data/iceberg.jpg')
mask_image = cv2.resize(mask_image, (300,400))
back_image = cv2.resize(back_image, (300,400))

mask_ANDed = cv2.bitwise_and(mask_image, back_image)
mask_ORed = cv2.bitwise_or(mask_image, back_image)
mask_XORed = cv2.bitwise_xor(mask_image, back_image)
mask_Inverted = cv2.bitwise_and(cv2.bitwise_not(mask_image), back_image)

cv2.imshow('mask', mask_image)
cv2.imshow('back', back_image)
cv2.imshow('mask and', mask_ANDed)
cv2.imshow('mask or', mask_ORed)
cv2.imshow('mask xor', mask_XORed)
cv2.imshow('mask inv', mask_Inverted)

cv2.waitKey(0)
Out[8]:
-1

13.7 원하는 색깔 픽셀만 뽑아 보자

In [9]:
import numpy as np
import cv2

image = cv2.imread('d:/data/mandrill.png')
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

blue_low = np.array([80, 0, 0])
blue_high = np.array([130, 255, 255])

mask = cv2.inRange(image_hsv, blue_low, blue_high)

cv2.imshow('original', image)
cv2.imshow('mask', mask)
cv2.waitKey(0)
Out[9]:
-1
In [10]:
extracted = cv2.bitwise_and(image, image, mask=mask)

13.8 이미지에 필터를 씌워 보자

In [11]:
import numpy as np
import cv2

org = cv2.imread('d:/data/mandrill.png', 1)

kernel1 = np.ones((3,3), np.float32) / 9
kernel2 = np.ones((9,9), np.float32) / 81

averaged33 = cv2.filter2D(org, -1, kernel1)
averaged99 = cv2.filter2D(org, -1, kernel2)

cv2.imshow('original', org)
cv2.imshow('filtered1', averaged33)
cv2.imshow('filtered2', averaged99)

cv2.waitKey(0)
Out[11]:
-1

13.9 OpenCV로 이미지 필터링하기

In [12]:
import numpy as np
import cv2

org = cv2.imread('d:/data/mandrill.png', 1)

averaged33 = cv2.GaussianBlur(org, (3,3), 1)
averaged99 = cv2.GaussianBlur(org, (9,9), 1)

cv2.imshow('original', org)
cv2.imshow('Gaussian 33', averaged33)
cv2.imshow('Gaussian 99', averaged99)
cv2.waitKey(0)
Out[12]:
-1

13.10 다양한 흐림 필터로 잡음을 제거해 보자

In [13]:
import numpy as np
import cv2

original_image = cv2.imread('d:/data/mandrill.png', 1)
result_image1 = cv2.GaussianBlur(original_image,  (9,9), 1)
result_image2 = cv2.medianBlur(original_image,  9)
result_image3 = cv2.bilateralFilter(original_image,  9, 50, 50)

13.11 관심있는 곳만 남겨보자

In [14]:
import cv2
global color_image, gray_image

# Æ®·¢¹Ù°¡ º¯°æµÇ¸é ±× °ªÀ» ÀÓ°èÄ¡·Î ȸ»öÁ¶ À̹ÌÁö¸¦ ÀÌÁøÈ­ÇÏ¿© â¿¡ ±×¸²
def on_change_threshold(x):
   _, th_image = cv2.threshold(gray_image, x, 255, cv2.THRESH_BINARY)
   cv2.imshow('Thresholding', th_image)

# À©µµ¸¦ »ý¼ºÇÔ
cv2.namedWindow('Thresholding')
cv2.createTrackbar('threshold', 'Thresholding', 0, 255, on_change_threshold)

# ÃÐºÒ À̹ÌÁö¸¦ Àаí, ȸ»öÁ¶ À̹ÌÁö¸¦ ÁغñÇÔ
color_image = cv2.imread('d:/data/candles.jpg', cv2.IMREAD_COLOR)
gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)

# óÀ½¿¡´Â ¿øº» À̹ÌÁö¸¦ ±×¸² (Æ®·¢¹Ù¸¦ º¯°æÇϸé ÀÓ°èÄ¡¿¡ µû¶ó ÀÌÁøÈ­ °á°ú Ãâ·Â)
cv2.imshow('Thresholding', color_image)

cv2.waitKey(0)
Out[14]:
-1
In [15]:
# image¸¦ ȸ»öÁ¶·Î ÀоîµéÀδÙ.
img_gray = cv2.imread('d:/data/green_back.png', cv2.IMREAD_GRAYSCALE)

# adaptiveThreshold¸¦ Àû¿ëÇÑ´Ù
# ÁÖº¯ 9x9 Çȼ¿ °ø°£ÀÇ Æò±Õ°ª - 5°¡ ÀÓ°èÄ¡°¡ µÇ°í, À̺¸´Ù Å©¸é 255, ±×·¸Áö ¾ÊÀ¸¸é 0
img_edge = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                cv2.THRESH_BINARY,   blockSize=9,   C= 0)

# °á°ú´Â À±°û¼± Çȼ¿ÀÌ µå·¯³­´Ù
cv2.imshow('edge', img_edge)
cv2.waitKey(0)
Out[15]:
-1

13.12 윤곽선을 더 잘 뽑아 낼 수 있을까

In [16]:
img = cv2.imread('d:/data/book.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)

cv2.imshow('gray', gray)
cv2.imshow('binary', thresh)

cv2.waitKey(0)
cv2.destroyAllWindows()

LAB13-1

합성 사진 만들기

In [17]:
img_hsv = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV) # HSV °ø°£À¸·Î 
l_bound = np.array([40, 100, 50])               # ³ì»ö »ö»ó ÇÏÇÑ
u_bound = np.array([80, 255, 255])              # ³ì»ö »ö»ó »óÇÑ

mask = cv2.inRange(img_hsv, l_bound, u_bound)   # ³ì»ö Çȼ¿ ã±â
mask_inv = cv2.bitwise_not(mask)                # ³ì»ö ¾Æ´Ñ Çȼ¿ ã±â
In [18]:
import numpy as np
import cv2

img1 = cv2.imread('d:/data/green_back.png')   # Àü°æ À̹ÌÁö Àбâ
img2 = cv2.imread('d:/data/iceberg.png')      # ¹è°æ À̹ÌÁö Àбâ

front_image = cv2.resize(mask_image, (300,400))
back_image = cv2.resize(back_image, (300,400))

img_hsv = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV) # HSV °ø°£À¸·Î ¿Å±è
l_bound = np.array([40, 100, 50])               # ³ì»ö »ö»óÀÇ ÇÏÇÑ
u_bound = np.array([80, 255, 255])              # ³ì»ö »ö»óÀÇ »óÇÑ
In [19]:
mask = cv2.inRange(img_hsv, l_bound, u_bound)    # ³ì»ö Çȼ¿ ã±â
mask_inv = cv2.bitwise_not(mask)                 # ³ì»öÀÌ ¾Æ´Ñ Çȼ¿ ã±â

# ³ì»ö Çȼ¿µé¸¸ ÃßÃâÇϱâ
extracted = cv2.bitwise_and(front_image, front_image, mask = mask) 
# ³ì»ö ¾Æ´Ñ Çȼ¿¸¸ ÃßÃâÇϱâ
removed = cv2.bitwise_and(front_image, front_image, mask = mask_inv)   
# ³ì»ö°ú °ãÄ¡´Â ¹è°æ ÃßÃâ
background = cv2.bitwise_and(back_image, back_image, mask=mask)   
# ³ì»ö Á¦°Å Àü°æ + ¹è°æ   
merged = cv2.bitwise_or(removed, background)
             
cv2.imshow('mask', mask)
cv2.imshow('mask_inv', mask_inv)
cv2.imshow('removed', removed)
cv2.imshow('background', background)
cv2.imshow('merged', merged)

cv2.waitKey(0) 
Out[19]:
-1

LAB13-2

텍스트 데이터 추출을 위한 준비

In [20]:
img = cv2.imread('d:/data/book.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)

cv2.imshow('gray', gray)
cv2.imshow('binary', thresh)
In [21]:
import numpy as np
import cv2
In [22]:
img = cv2.imread('d:/data/book.png')

# ÀâÀ½Àº Á¦°ÅÇϸ鼭 Ư¡Àº À¯ÁöÇÒ ¼ö ÀÖ´Â ¾ç¹æÇâ ÇÊÅÍ Àû¿ë
blur_bilateral = cv2.bilateralFilter(img, 11, 75, 75)   

# ȸ»öÁ¶·Î º¯È¯
gray = cv2.cvtColor(blur_bilateral, cv2.COLOR_BGR2GRAY) 

# Àα٠Çȼ¿°ú ºñ±³ÇÑ ÀÌÁøÈ­
thresh = cv2.adaptiveThreshold(gray, 255,                            
         cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 7)

cv2.imshow('original', img)
cv2.imshow('bilateral', blur_bilateral)
cv2.imshow('gray', gray)
cv2.imshow('binary', thresh)

cv2.waitKey(0)
Out[22]:
-1