OpenCV-Python入門教程3-圖像基本操作(訪問像素點/ROI/通道分離)


一、獲取和修改像素點的值

import cv2
img = cv2.imread('lena.jpg')
# 100, 90表示行列坐標
px = img[100, 90]
print(px)

# 獲取一個坐標單通道的值
# 0:藍色(B)
# 1:綠色(G)
# 2:紅色(R)
px_blue = img[100, 90, 0]

px_green = img[100, 90, 1]
px_red = img[100, 90, 2]
print(px_blue)
print(px_green)
print(px_red)
[103  98 197]
103
98
197

通過行、列坐標獲取某個像素點的值,對於彩色圖。B、G、R對應0, 1, 2

修改像素也是同樣的方式:

# 修改像素的值
img[100, 90] = [255, 255, 255]
print(img[100, 90])
[255 255 255]
注意:該操作只是內存中的img像素點變了,因為沒有保存,所以原圖並沒有修改

更好的像素訪問和編輯方法:

img.item(100, 90, 0)
103
# 修改藍色通道的值
img.itemset((100, 90, 0), 50)
img.item(100, 90, 0)
50

二、圖片屬性

1、圖像形狀

print(img.shape)
# 形狀中包括行數,列數和通道數
height, width, channels = img.shape
# img是灰度圖,height, width = img.shape
(263, 247, 3)

2、數據類型

print(img.dtype)
uint8

3、圖像總像素數

print(img.size) # 263 * 247 * 3 = 194883
194883

二、感興趣區域(ROI)

# 截取臉部ROI
face = img[100:200, 115:188]
cv2.imshow('face', face)
cv2.waitKey(0)

行對應y,列對應x,所以其實是img[y, x],所以要注意,不要弄混淆

三、通道分割與合並

b, g, r = cv2.split(img)
img = cv2.merge((b, g, r))

分割:cv2.split()    合並:cv.merge()

split()函數比較耗時,更高效的方式是用numpy中的索引,提取B通道:

b = img[:, :, 0]
cv2.imshow('blue', b)
cv2.waitKey(0)

由於是單通道圖,所以呈現出來的是一種灰度圖。

 參考網址:https://tianchi.aliyun.com/course/courseConsole?courseId=40992&chapterIndex=1&sectionIndex=4

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM