欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-07-29 07:42:52|栏目:Python代码|点击:

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

上一篇:Python中的with...as用法介绍

栏    目:Python代码

下一篇:python 利用turtle模块画出没有角的方格

本文标题:python统计RGB图片某像素的个数案例

本文地址:http://www.codeinn.net/misctech/162399.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有