python統(tǒng)計(jì)RGB圖片某像素的個數(shù)案例
1.對于RGB三通道圖片,直接用兩層for循環(huán)的話,效率比較低
2.可以先將RGB圖片轉(zhuǎn)為灰度圖片,再利用numpy.where的廣播機(jī)制統(tǒng)計(jì)像素個數(shù)。這里有一個前提是提前知道與灰度圖片的像素值相對應(yīng)RGB顏色。
代碼如下:
from PIL import Imageimport numpy as npimport cv2img_L = np.array(Image.open(’test.png’).convert('L'))img_RGB = np.array(Image.open(’test.png’).convert('RGB'))# temp = {}# for i in range(img_L.shape[0]):# for j in range(img_L.shape[1]):# if not temp.get(int(img_L[i][j])):# temp[int(img_L[i][j])] = list(img_RGB[i][j])# print(temp)#這里得到灰度像素值0對應(yīng)(0,0,0),62對應(yīng)(19,69,139)color_0_0_0 = np.where(img_L == 0)[0].shape[0]color_19_69_139 = np.where(img_L == 62)[0].shape[0]pixel_sum = img_L.shape[0] * img_L.shape[1]print('0_0_0 像素個數(shù):{} 占比:%{}'.format(color_0_0_0,color_0_0_0/pixel_sum*100))print('19_69_139 像素個數(shù):{} 占比:%{}'.format(color_19_69_139,color_19_69_139/pixel_sum*100))
補(bǔ)充:OpenCV---如何統(tǒng)計(jì)圖像的像素分布值個數(shù)(6)
代碼如下:import cv2 as cvimport matplotlib.pyplot as pltimport numpy as npdef statistics(): src = cv.imread('D:/matplotlib/0.jpg') cv.imshow('q',src) h,w,ch = np.shape(src) gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY) cv.imshow('gray',gray) hest = np.zeros([256],dtype = np.int32) for row in range(h): for col in range(w): pv = gray[row,col] hest[pv] +=1 plt.plot(hest,color = 'r') plt.xlim([0,256]) plt.show() cv.waitKey(0) cv.destroyAllWindows()statistics()運(yùn)行效果:
像素分布統(tǒng)計(jì)圖
代碼解釋:import cv2 as cvimport matplotlib.pyplot as pltimport numpy as npdef statistics(): src = cv.imread('D:/matplotlib/0.jpg') cv.imshow('q',src) h,w,ch = np.shape(src) #讀取圖像屬性 gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY) #將圖像轉(zhuǎn)換成灰度圖, cv.imshow('gray',gray) hest = np.zeros([256],dtype = np.int32) #建立空白數(shù)組 for row in range(h): for col in range(w): pv = gray[row,col] hest[pv] +=1 #統(tǒng)計(jì)不同像素值出現(xiàn)的頻率 plt.plot(hest,color = 'r') plt.xlim([0,256]) plt.show() #畫出統(tǒng)計(jì)圖 cv.waitKey(0) cv.destroyAllWindows()statistics()
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. vue實(shí)現(xiàn)web在線聊天功能2. JavaScript實(shí)現(xiàn)頁面動態(tài)驗(yàn)證碼的實(shí)現(xiàn)示例3. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis4. Springboot 全局日期格式化處理的實(shí)現(xiàn)5. SpringBoot+TestNG單元測試的實(shí)現(xiàn)6. 完美解決vue 中多個echarts圖表自適應(yīng)的問題7. 解決Android Studio 格式化 Format代碼快捷鍵問題8. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)9. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼10. Java使用Tesseract-Ocr識別數(shù)字
