openCV3 - 2

創造一張圖

  1. 長400,寬400,三通道圖。色彩值(0,0,255),紅色。
  2. 長400,寬400,單通道圖。色彩值127,灰色。
import cv2 as cv
def create_image():
    img = np.zeros([400, 400, 3], np.uint8)
    img[:, :, 2] = np.ones([400, 400])*255
    cv.imshow("new image",img)

    img = np.zeros([400, 400, 1], np.uint8)
    img[:, :, 0] = np.ones([400, 400]) * 127
    cv.imshow("new image", img)
    

numpy的一些基礎用法

import numpy as np
mt = np.ones([3, 3], np.uint8)
mt.fill(122.388)
print(mt)


"""
[[122 122 122]
 [122 122 122]
 [122 122 122]]
"""

通道分離與合併

  • cv.split()
  • cv.merge()
    合併單通道成爲多通道,而不能多通道合併。
src = cv.imread("test.png")  # blue, green, red
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
# cv.imshow("input image", src)

b, g, r = cv.split(src)

cv.imshow("blue", b)
cv.imshow("green", g)
cv.imshow("red", r)

# 恢復原圖
# src = cv.merge([r, g, b])

CPP

bool split3channels()
{
    vector<Mat> channels;
    Mat srcImage = imread("/Users/sxt/Downloads/17/mogu.jpg");
    split(srcImage, channels);
    Mat blueChannles = channels.at(0);
    Mat greenChannels = channels.at(1);
    Mat redChannels = channels.at(2);
}

結果全是單通道圖片。
帶顏色的是三通道圖片,在split分離出的圖像基礎上,擴展另外兩個通道(爲0)。
如下:

# 生成一個值爲0的單通道數組
zeros = np.zeros(image.shape[:2], dtype = "uint8")

# 分別擴展B、G、R成爲三通道。另外兩個通道用上面的值爲0的數組填充
cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))
cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
cv2.imshow("Red", cv2.merge([zeros, zeros, R]))
cv2.waitKey(0)

src[:, :, 0] = 0
src[:, :, 1] = 0
cv.imshow("Red src", src)

Python運算時間

t1 = cv.getTickCount()
t2 = cv.getTickCount()
time = (t2 - t1) / cv.getTickFrequency()

生成灰度圖並且寫入

單通道

src = cv.imread("test.png")  # blue, green, red
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imwrite("result1.png", gray)
cv.waitKey(0)
cv.destroyAllWindows()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章