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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

概率问题   2021-03-17 我要评论
想了解python统计RGB图片某像素的个数案例的相关内容吗,概率问题在本文为您仔细讲解python统计图片像素的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,RGB图片,统计像素,下面大家一起来学习吧。

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()

运行效果:

像素分布统计图

代码解释:

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()

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们