Skip to content

Instantly share code, notes, and snippets.

@yunwoong7
Last active December 10, 2021 06:44
Show Gist options
  • Save yunwoong7/2b47222092b50016760ab3e989b560aa to your computer and use it in GitHub Desktop.
Save yunwoong7/2b47222092b50016760ab3e989b560aa to your computer and use it in GitHub Desktop.
scikit-image 정리

scikit-image

scikit-image는 이미지처리에 특화된 Python 이미지 라이브러리이며 Numpy배열로 이미지 객체를 네이티브하게 다룹니다.

설치

pip 또는 Anaconda를 통해 설치를 진행합니다.

pip install scikit-image
conda install -c conda-forge scikit-image

기본적으로 이미지를 자른다던가 단순한 필터링 등의 이미지 조작이 가능하고 Numpy 배열로 동작하기때문에 Numpy를 활용한 연산이 쉽습니다.
일부 Pillow보다 고급 기능을 제공하기도 하고 픽셀 값이 0과 1사이에 있는 float 이미지를 다룰 수도 있습니다.

from skimage import io
import os

result_dir = "result"

# Make Directory
if not os.path.exists(result_dir):
    os.makedirs(result_dir)

1. 이미지 열기

imshow() 함수는 Matplotlib를 사용하여 이미지를 표시 합니다.

image = io.imread("images/test_image/test_image.jpg")
io.imshow(image)

<matplotlib.image.AxesImage at 0x2489fbb8160>

2. 이미지 속성

imread() 함수로 이미지를 Load한 이미지는 numpy array 이기때문에 속성 정보는 사이즈와 채널 정보 정도만 알 수 있습니다.

print('이미지 사이즈 : {}'.format(image.shape))
print('이미지 Width : {}'.format(image.shape[0]))
print('이미지 Height : {}'.format(image.shape[1]))

이미지 사이즈 : (1028, 1024, 3) 이미지 Width : 1028 이미지 Height : 1024

3. 이미지 크기 변경

from skimage.transform import rescale, resize, downscale_local_mean

image = io.imread("images/test_image/image_1.jpg")

# 크기를 1/6 size로 변경
image_resized = resize(image, (image.shape[0] // 6, image.shape[1] // 6), anti_aliasing=True)

print("Resize {} -> {}".format(image.shape, image_resized.shape))
io.imshow(image_resized)

Resize (1028, 1024, 3) -> (171, 170, 3) <matplotlib.image.AxesImage at 0x248a1007f70>

4. 이미지 회전

from skimage.transform import rotate

image = io.imread("images/test_image/test_image.jpg")

# 90도 회전
rotate_image = rotate(image, 90, resize=True)

io.imshow(rotate_image)

<matplotlib.image.AxesImage at 0x248a134f910>

5. 이미지 상하, 좌우 대칭(Flip)

import numpy as np

# 좌우대칭
filp_lr_image = np.fliplr(image)
io.imshow(filp_lr_image)

<matplotlib.image.AxesImage at 0x248a13b2e50>

# 상하반전
filp_ud_image = np.flipud(image)
io.imshow(filp_ud_image)

<matplotlib.image.AxesImage at 0x248a1416fa0>

6. 이미지 자르기(Crop)

[y1:y2, x1:x2]

image = io.imread("images/test_image/test_image.jpg")

cropped_image = image[520:580, 480:580]
io.imshow(cropped_image)

<matplotlib.image.AxesImage at 0x248a2ad9910>

7. Draw Box

import numpy as np
from skimage import io, draw

image = io.imread("images/test_image/test_image.jpg")
image_resized = resize(image, (image.shape[0] // 6, image.shape[1] // 6), anti_aliasing=True)

color = np.array([0, 255, 0], dtype=np.uint8)
# x1, y1, w, h
bounding_box = (80, 85, 15, 11)

image_resized[bounding_box[1], bounding_box[0]:bounding_box[0] + bounding_box[2]] = color
image_resized[bounding_box[1]:bounding_box[1] + bounding_box[3], bounding_box[0]] = color

image_resized[bounding_box[1] + bounding_box[3], bounding_box[0]:bounding_box[0] + bounding_box[2]] = color
image_resized[bounding_box[1]:bounding_box[1] + bounding_box[3], bounding_box[0] + bounding_box[2]] = color

io.imshow(image_resized)

<matplotlib.image.AxesImage at 0x248a52a31f0>

8. 이미지 필터링

from skimage import filters
from skimage import io

image = io.imread("images/test_image/test_image.jpg")
gaussian_filter_image = filters.gaussian(image, sigma=10)

io.imshow(gaussian_filter_image)

<matplotlib.image.AxesImage at 0x248a5ba2070>

9. 이미지 합치기

merge_image = np.concatenate((filp_lr_image, filp_ud_image), axis=1)
io.imshow(merge_image)

<matplotlib.image.AxesImage at 0x248a60f64c0>

10. 색상 모듈

from skimage import io
from skimage import color
import matplotlib.pyplot as plt

image = io.imread("images/test_image/test_image.jpg")
gray_image = color.rgb2gray(image)
hsv_image = color.rgb2hsv(image)

fig, axes = plt.subplots(nrows=1, ncols=2)
ax = axes.ravel()

ax[0].imshow(gray_image)
ax[0].set_title("Gray image")

ax[1].imshow(hsv_image)
ax[1].set_title("HSV image")

Text(0.5, 1.0, 'HSV image')

11. ORB feature detector and binary descriptor

from skimage import transform
from skimage.color import rgb2gray
from skimage.feature import (match_descriptors, corner_harris, corner_peaks, ORB, plot_matches)
import matplotlib.pyplot as plt

image1 = io.imread("images/test_image/test_image.jpg")
image1 = rgb2gray(image1)
image2 = rotate(image1, 180, resize=True)

descriptor_extractor = ORB(n_keypoints=200)
descriptor_extractor.detect_and_extract(image1)
keypoints1 = descriptor_extractor.keypoints
descriptors1 = descriptor_extractor.descriptors

descriptor_extractor.detect_and_extract(image2)
keypoints2 = descriptor_extractor.keypoints
descriptors2 = descriptor_extractor.descriptors

matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)

fig, ax = plt.subplots(nrows=1, ncols=1)
plt.gray()

ax.axis('off')
ax.set_title("Original Image vs. Transformed Image")
plot_matches(ax, image1, image2, keypoints1, keypoints2, matches12)

12. BRIEF binary descriptor

from skimage import transform
from skimage.feature import (match_descriptors, corner_peaks, corner_harris, plot_matches, BRIEF)
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

image1 = io.imread("images/test_image/image_1.jpg")
image1 = rgb2gray(image1)
image2 = rotate(image1, 60, resize=True)

keypoints1 = corner_peaks(corner_harris(image1), min_distance=5, threshold_rel=0.1)
keypoints2 = corner_peaks(corner_harris(image2), min_distance=5, threshold_rel=0.1)

extractor = BRIEF()

extractor.extract(image1, keypoints1)
keypoints1 = keypoints1[extractor.mask]
descriptors1 = extractor.descriptors

extractor.extract(image2, keypoints2)
keypoints2 = keypoints2[extractor.mask]
descriptors2 = extractor.descriptors

matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)

fig, ax = plt.subplots(nrows=1, ncols=1)
plt.gray()

ax.axis('off')
ax.set_title("Original Image vs. Transformed Image")
plot_matches(ax, image1, image2, keypoints1, keypoints2, matches12)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment