引言
此係列博客記錄 網易雲課堂 python + openCV圖像處理課程的學習過程。
本篇博客將介紹 讀取、顯示、保存圖像,讀取、修改 像素值(openCV 與 numpy) 三個部分。
介紹
OpenCV (Open Source Computer Vision Library) is released under a BSD license and hence it’s free for both academic and commercial use. It has C++, Python and Java interfaces and supports Windows, Linux, Mac OS, iOS and Android.
OpenCV was designed for computational efficiency and with a strong focus on real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing.
Enabled with OpenCL(一個爲異構平臺編寫程序的框架), it can take advantage of the hardware acceleration of the underlying heterogeneous compute platform.
圖像基礎
1、圖像都是由像素構成的,在同等面積下,像素點越多,圖像越細膩。
2、圖像分類:
- 二值圖像:圖像只有 黑、白 兩種顏色(像素點 0 或 1)
- 灰度圖像:圖像只有 黑、白、灰 三種顏色(像素點 0 - 255,其中 0 爲黑色,255 爲白色,1-254 之間均爲灰色)
- RGB圖像:彩色圖像
tips: 二值和灰度圖像 均爲 單通道,RGB圖像 爲 三通道。
3、彩色圖像(RGB):由 紅、綠、藍 三色 按照某種比例混合而成的。
- 比如:
(255,182,193)
表示淺粉紅色,更常用的16進制 -#FFB6C1
4、彩色圖像(BGR):openCV
庫 專用,順序爲 藍、綠、紅 。
代碼
1、讀取、顯示、保存圖像
# -*- coding: utf-8 -*-
import cv2 # 導入 openCV 庫
i = cv2.imread(r"C:\workspace\python\openCV\test.jpg") # 讀取
cv2.imshow("Demo",i) # 顯示
cv2.waitKey(0) # 窗口等待
cv2.destroyAllWindows() # 從內存中釋放
cv2.imwrite(r"C:\workspace\python\openCV\test1.jpg",i) # 保存
其中,# -*- coding: utf-8 -*-
設置編碼格式爲 utf-8 , 僅 python2 才需要(若沒有,則無法使用中文註釋)
imread("path",param)
,其中 path 爲圖片的路徑,param 爲顯示控制參數:
cv2.IMREAD_UNCHANGED
- 以 原圖形式 讀入cv2.IMREAD_GRAYSCALE
- 以 灰度形式 讀入cv2.IMREAD_COLOR
- 以 彩色形式 讀入
imshow("name",image)
,其中 name 爲窗口名稱,image 爲讀取的圖片對象。
waitKey(delay)
,其中 delay 爲窗口的等待時間。
delay > 0
- 等待 delay 毫秒delay < 0
- 等待鍵盤單擊delay = 0
- 無限等待delay = null
- 等待鍵盤單擊
imwrite("path",image)
,其中 path 爲保存圖片的路徑(自定義名稱),image 爲讀取的圖片對象
2、讀取、修改 像素值(openCV)
import cv2
#BGR圖像
i = cv2.imread(r"C:\workspace\python\openCV\color.jpg",cv2.IMREAD_UNCHANGED) # BGR圖像,三通道
print(i[20,20]) # 結果 [255 248 255]
'''
修改像素方式一:統一修改
'''
i[20,20] = [0,0,0]
print(i[20,20]) # 結果 [0 0 0]
'''
修改像素方式二:逐 通道 修改
'''
i[20,20,0] = 0 # 藍 Blue 通道
i[20,20,1] = 1 # 綠 Green 通道
i[20,20,2] = 2 # 紅 Red 通道
print(i[20,20]) # 結果 [0 1 2]
#灰度圖像
g = cv2.imread(r"C:\workspace\python\openCV\gray.jpg",cv2.IMREAD_UNCHANGED) # 灰度圖像,單通道
print(g[20,20]) # 結果 255
g[20,20] = 0
print(g[20,20]) # 結果 0
其中,i[20,20]
表示 圖片 i 中第20行,20列的像素
3、讀取、修改 像素值(numpy)
import cv2
import numpy as np
i = cv2.imread(r"C:\workspace\python\openCV\color.jpg",cv2.IMREAD_UNCHANGED) # BGR圖像,三通道
print(i.item(20,20,0)) # B 通道 255
i.itemset((20,20,0),0)
print(i.item(20,20,0)) # 結果 0
print(i.item(20,20,1)) # G 通道 248
i.itemset((20,20,1),1)
print(i.item(20,20,1)) # 結果 1
print(i.item(20,20,2)) # R 通道 255
i.itemset((20,20,2),2)
print(i.item(20,20,2)) #結果 2
g = cv2.imread(r"C:\workspace\python\openCV\gray.jpg",cv2.IMREAD_UNCHANGED) # 灰度圖像,單通道
print(g.item(20,20)) # 結果 255
g.itemset((20,20),7)
print(g.item(20,20)) # 結果 7
item(x,y)
- 讀取 (x,y) 座標的像素值,單通道
item(x,y,n)
- 讀取 (x,y) 座標的像素值, 三通道,n 是通道(0-B,1-G,2-R)
itemset((x,y),k)
- 修改 (x,y) 座標的像素值,k是新賦的值
itemset((x,y,n),k)
- 修改 (x,y) 座標的像素值,k是新賦的值,n 是通道(0-B,1-G,2-R)