2017-05-06 28 views
1

我正在使用opencv,我可以通过下面的代码获取图像的像素 - 一个三维元组。但是,我不太清楚如何计算图像中像素值的模式。如何找到图像像素值的模式(统计)?

import cv2 
import numpy as np 
import matplotlib.pyplot as plt 

import numpy as np 
import cv2 


img =cv2.imread('C:\\Users\Moondra\ABEO.png') 

#px = img[100,100] #gets pixel value 
#print (px) 

我试过,

from scipy import stats 
stats.mode(img)[0] 

但这返回

stats.mode(img)[0].shape 
(1, 800, 3) 

不知道究竟stats的计算,从中选择模式的尺寸阵列状,但我m查找每个像素值(3维元组)为一个元素。

编辑: 为了清楚起见,我将阐述我正在寻找的东西。 比方说,我们有一个数组,它是形状(3,5,3)的,看起来像这样

array([[[1, 1, 2], #[1,1,2] = represents the RGB values 
     [2, 2, 2], 
     [1, 2, 2], 
     [2, 1, 1], 
     [1, 2, 2]], 

     [[1, 2, 2], 
     [2, 2, 2], 
     [2, 2, 2], 
     [1, 2, 2], 
     [1, 2, 1]], 

     [[2, 2, 1], 
     [2, 2, 1], 
     [1, 1, 2], 
     [2, 1, 2], 
     [1, 1, 2]]]) 

然后我会把它转换成一个数组,看起来像这样更容易计算

打开本成

array([[1, 1, 2], 
     [2, 2, 2], 
     [1, 2, 2], 
     [2, 1, 1], 
     [1, 2, 2], 

     [1, 2, 2], 
     [2, 2, 2], 
     [2, 2, 2], 
     [1, 2, 2], 
     [1, 2, 1], 

     [2, 2, 1], 
     [2, 2, 1], 
     [1, 1, 2], 
     [2, 1, 2], 
     [1, 1, 2]]) 


which is of shape(15,3) 

我想通过计数每一组RGB的计算模式,如下所示:

[1,1,2] = 3 
[2,2,2] = 4 
[1,2,2] = 4 
[2,1,1] = 2 
[1,1,2] =1 

谢谢。

+2

'stats.mode(IMG,轴= -1)[0]'? – Divakar

+0

去测试一下。 – Moondra

+0

用'axis = 0,1,2和-1'进行快速测试,仍然会产生一个大的数组。要重新测试。 – Moondra

回答

2

从描述中看,您似乎是在输入图像中发生最多的像素之后。为了解决对于相同的,这是一个使用的views概念一个有效的方法 -

def get_row_view(a): 
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[-1]))) 
    a = np.ascontiguousarray(a) 
    return a.reshape(-1, a.shape[-1]).view(void_dt).ravel() 

def get_mode(img): 
    unq, idx, count = np.unique(get_row_view(img), return_index=1, return_counts=1) 
    return img.reshape(-1,img.shape[-1])[idx[count.argmax()]] 

样品运行 -

In [69]: img = np.random.randint(0,255,(4,5,3)) 

In [70]: img.reshape(-1,3)[np.random.choice(20,10,replace=0)] = 120 

In [71]: img 
Out[71]: 
array([[[120, 120, 120], 
     [ 79, 105, 218], 
     [ 16, 55, 239], 
     [120, 120, 120], 
     [239, 95, 209]], 

     [[241, 18, 221], 
     [202, 185, 142], 
     [ 7, 47, 161], 
     [120, 120, 120], 
     [120, 120, 120]], 

     [[120, 120, 120], 
     [ 62, 41, 157], 
     [120, 120, 120], 
     [120, 120, 120], 
     [120, 120, 120]], 

     [[120, 120, 120], 
     [ 0, 107, 34], 
     [ 9, 83, 183], 
     [120, 120, 120], 
     [ 43, 121, 154]]]) 

In [74]: get_mode(img) 
Out[74]: array([120, 120, 120]) 
+0

那么它是分别计算每个通道的模式值,而不是一起计算?所以它不会是一个真正的像素值吗? – Moondra

+0

@moondra你怎么能模式计算所有R,G,B通道在一起,并最终形成(1,1,3)形输出?我想你应该模拟一个样本“(4,5,3)”形图像阵列,并向我们解释你究竟是什么。 – Divakar

+0

好的,会加。给我第二。 – Moondra