数字图像与机器视觉基础补充(补)

数字图像与机器视觉基础补充

彩色图像文件转换为灰度文件

使用opencv

代码:

import cv2 as cv

img = cv.imread('189.png', 1)
img_1 = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('gray', img_1)
cv.imshow('colour', img)
cv.waitKey(0)

数字图像与机器视觉基础补充(补)

不使用opencv

from PIL import Image

I = Image.open('189.png')
L = I.convert('L')
L.show()

数字图像与机器视觉基础补充(补)

彩色图像(RGB)转为HSV、HSI 格式

HSV

import cv2 as cv

img = cv.imread('189.png', 1)
cv.imshow('original image', img)
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow('HSV format image', hsv)
cv.waitKey(0)

数字图像与机器视觉基础补充(补)
数字图像与机器视觉基础补充(补)

HSI

import cv2
import numpy as np


def rgbtohsi(rgb_lwpImg):
    rows = int(rgb_lwpImg.shape[0])
    cols = int(rgb_lwpImg.shape[1])
    b, g, r = cv2.split(rgb_lwpImg)
    # 归一化到[0,1]
    b = b / 255.0
    g = g / 255.0
    r = r / 255.0
    hsi_lwpImg = rgb_lwpImg.copy()
    H, S, I = cv2.split(hsi_lwpImg)
    for i in range(rows):
        for j in range(cols):
            num = 0.5 * ((r[i, j] - g[i, j]) + (r[i, j] - b[i, j]))
            den = np.sqrt((r[i, j] - g[i, j]) ** 2 + (r[i, j] - b[i, j]) * (g[i, j] - b[i, j]))
            theta = float(np.arccos(num / den))

            if den == 0:
                H = 0
            elif b[i, j] <= g[i, j]:
                H = theta
            else:
                H = 2 * 3.14169265 - theta

            min_RGB = min(min(b[i, j], g[i, j]), r[i, j])
            sum = b[i, j] + g[i, j] + r[i, j]
            if sum == 0:
                S = 0
            else:
                S = 1 - 3 * min_RGB / sum

            H = H / (2 * 3.14159265)
            I = sum / 3.0
            # 输出HSI图像,扩充到255以方便显示,一般H分量在[0,2pi]之间,S和I在[0,1]之间
            hsi_lwpImg[i, j, 0] = H * 255
            hsi_lwpImg[i, j, 1] = S * 255
            hsi_lwpImg[i, j, 2] = I * 255
    return hsi_lwpImg


if __name__ == '__main__':
    rgb_lwpImg = cv2.imread("1.jpg")
    hsi_lwpImg = rgbtohsi(rgb_lwpImg)
    cv2.imshow('1.jpg', rgb_lwpImg)
    cv2.imshow('hsi_lwpImg', hsi_lwpImg)
    key = cv2.waitKey(0) & 0xFF
    if key == ord('q'):
        cv2.destroyAllWindows()

数字图像与机器视觉基础补充(补)

参考

将彩色图像转换为灰度文件、HSV、HSI 格式

上一篇:Ehcache教程


下一篇:[译] EF 6 新特性 - 中