{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# 引入影象處理庫OpenCV\n", "import cv2" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# 引入numpy庫,並以np當別名\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# 讀取圖片\n", "img = cv2.imread('data/image/logo.png')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# 第一種方式" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# 分割圖片通道\n", "B, G, R = cv2.split(img)\n", "\n", "# 宣告一個值為0的單通道數組\n", "# img.shape[:2] = (img.shape[0], img.shape[1])\n", "zeros = np.zeros(img.shape[:2], dtype = \"uint8\")\n", "\n", "# 分別擴展B、G、R成為三通道。另外兩個通道用上面的值為0的數組填充\n", "B = cv2.merge([B, zeros, zeros])\n", "G = cv2.merge([zeros, G, zeros])\n", "R = cv2.merge([zeros, zeros, R])" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# 第二種方法" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# 複製原圖(三通道)\n", "B = img.copy()\n", "G = img.copy()\n", "R = img.copy()\n", "\n", "# set green and red channels to 0\n", "B[:, :, 1] = 0\n", "B[:, :, 2] = 0\n", "\n", "# set blue and red channels to 0\n", "G[:, :, 0] = 0\n", "G[:, :, 2] = 0\n", "\n", "# set blue and green channels to 0\n", "R[:, :, 0] = 0\n", "R[:, :, 1] = 0" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# 持續等待按鍵,並刷新\n", "cv2.waitKey(0)\n", "\n", "# 關閉所有OpenCV視窗\n", "cv2.destroyAllWindows()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# 將圖片儲存至指定位置\n", "cv2.imwrite('data/image/B.jpg', B)\n", "cv2.imwrite('data/image/G.jpg', G)\n", "cv2.imwrite('data/image/R.jpg', R)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 持續等待按鍵,並刷新\n", "cv2.waitKey(0)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# 關閉所有OpenCV視窗\n", "cv2.destroyAllWindows()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 2 }