cv2 inrange灰度图_Python opencv将图片转为灰度图的方法示例
這篇文章主要介紹了python opencv將圖片轉(zhuǎn)為灰度圖的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
使用opencv將圖片轉(zhuǎn)為灰度圖主要有兩種方法,第一種是將彩色圖轉(zhuǎn)為灰度圖,第二種是在使用OpenCV讀取圖片的時候直接讀取為灰度圖。
將彩色圖轉(zhuǎn)為灰度圖
import cv2
import numpy as np
if __name__ == "__main__":
img_path = "timg.jpg"
img = cv2.imread(img_path)
#獲取圖片的寬和高
width,height = img.shape[:2][::-1]
#將圖片縮小便于顯示觀看
img_resize = cv2.resize(img,
(int(width*0.5),int(height*0.5)),interpolation=cv2.INTER_CUBIC)
cv2.imshow("img",img_resize)
print("img_reisze shape:{}".format(np.shape(img_resize)))
#將圖片轉(zhuǎn)為灰度圖
img_gray = cv2.cvtColor(img_resize,cv2.COLOR_RGB2GRAY)
cv2.imshow("img_gray",img_gray)
print("img_gray shape:{}".format(np.shape(img_gray)))
cv2.waitKey()
img_reisze shape:(337, 600, 3)
img_gray shape:(337, 600)
使用opencv讀取圖片的時候,默認(rèn)使用的是BGR來讀取圖片的,可以看到原始讀取的圖片是3通道的,經(jīng)過轉(zhuǎn)換之后變成了單通道。
直接將圖片采用灰度圖的方式進(jìn)行讀取
import cv2
import numpy as np
if __name__ == "__main__":
img_path = "timg.jpg"
img = cv2.imread(img_path)
#獲取圖片的寬和高
width,height = img.shape[:2][::-1]
#將圖片縮小便于顯示觀看
img_resize = cv2.resize(img,
(int(width*0.5),int(height*0.5)),interpolation=cv2.INTER_CUBIC)
cv2.imshow("img",img_resize)
print("img_reisze shape:{}".format(np.shape(img_resize)))
#讀取灰度圖
img_gray = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)
#將圖片縮小便于顯示觀看
img_gray = cv2.resize(img_gray,
(int(width*0.5),int(height*0.5)),interpolation=cv2.INTER_CUBIC)
cv2.imshow("img_gray",img_gray)
print("img_gray shape:{}".format(np.shape(img_gray)))
cv2.waitKey()
img_reisze shape:(337, 600, 3)img_gray shape:(337, 600)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,更多關(guān)于Python類知識請關(guān)注我,分享更多噢!!!
總結(jié)
以上是生活随笔為你收集整理的cv2 inrange灰度图_Python opencv将图片转为灰度图的方法示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MapInfo开发心得——控件篇
- 下一篇: websocket python爬虫_p