python统计RGB图片某像素的个数案例

时间:2022-11-09 20:36:18

1.对于RGB三通道图片,直接用两层for循环的话,效率比较低

2.可以先将RGB图片转为灰度图片,再利用numpy.where的广播机制统计像素个数。这里有一个前提是提前知道与灰度图片的像素值相对应RGB颜色。

代码如下:

from PIL import Image
import numpy as np
import cv2

img_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对应(0,0,0),62对应(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 像素个数:{} 占比:%{}".format(color_0_0_0,color_0_0_0/pixel_sum*100))
print("19_69_139 像素个数:{} 占比:%{}".format(color_19_69_139,color_19_69_139/pixel_sum*100))

补充:OpenCV---如何统计图像的像素分布值个数(6)

代码如下:

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
def 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()

运行效果:

python统计RGB图片某像素的个数案例

python统计RGB图片某像素的个数案例

像素分布统计图

代码解释:

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
def 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()

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/qq_33768643/article/details/105724834