Python - 获取图像区域的平均RGB分量

时间:2017-03-07 05:18:54

标签: python numpy python-imaging-library

我需要计算红色,绿色和绿色的平均值。图像的蓝色分量值。图像不一定是方形的。它也可以是矩形。

图像分为4个象限,每个象限进一步分为2个三角形区域,图像中总共有8个区域(P1-P8)

# -------------------------
# - Q1        +        Q2 -   
# -        P8 + P1        -
# -      P7   +    P2     -
# -+++++++++++++++++++++++-
# -      P6   +    P3     -
# -        P5 + P4        -
# - Q4        +        Q3 -
# -------------------------

到目前为止,我已设法获取图像(主监视器屏幕截图)并将rgb值转换为numpy数组。

从那里我不确定获得三角形区域的最佳方法,因为我需要每秒至少进行3次此操作。

有什么想法吗?

import subprocess
import numpy
import pyscreenshot as ImageGrab

#GET THE PRIMARY MONITOR RESOLUTION
output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
primary_monitor_x = output.split("\n")[0].split("x")[0].strip()
primary_monitor_y = output.split("\n")[0].split("x")[1].strip()
print "primary monitor X = " + primary_monitor_x + "px"
print "primary monitor Y = " + primary_monitor_y + "px"

print ""
print ""

x_max = int(primary_monitor_x)
y_max = int(primary_monitor_y)

#GET SCREEN IMAGE IN A PIL IMAGE
im = ImageGrab.grab(bbox=(0,0,x_max,  y_max))
#CONVERT IMAGE TO RGB MODE
rgb_im = im.convert('RGB')

#CONVERT IMAGE TO NUMPY 2D ARRAY WITH EACH ELEMENT AS PIXEL RGB TUPLE
img_rgb_array = numpy.array(rgb_im);

#THE SCREEN IS DIVIDED INTO 8 PARTS. FOR EACH PART, THE AVERAGE VALUE
#OF RED, GREEN, BLUE COLOR COMPONENT WILL BE CALCULATED
# -------------------------
# - Q1        +        Q2 -   
# -        P8 + P1        -
# -      P7   +    P2     -
# -+++++++++++++++++++++++-
# -      P6   +    P3     -
# -        P5 + P4        -
# - Q4        +        Q3 -
# -------------------------

#SLICE THE IMAGE RGB ARRAY INTO 4 SMALLER QUADRANT ARRAYS
img_rgb_arraq_q1 = img_rgb_array[0:(y_max/2), 0:(x_max/2)]
img_rgb_arraq_q2 = img_rgb_array[0:(y_max/2), (x_max/2):x_max]
img_rgb_arraq_q3 = img_rgb_array[(y_max/2):y_max, (x_max/2):x_max]
img_rgb_arraq_q4 = img_rgb_array[(y_max/2):y_max, 0:(x_max/2)]

1 个答案:

答案 0 :(得分:0)

对于正方形Q2Q4,您可以执行类似

的操作
import numpy as np

n = 5
a = np.arange(n**2).reshape((n,n))

idx = np.fromfunction(lambda i,j: i+j<n, (n,n))
# use i+j<n-1 if the diagonal should go to the lower triangular

a_upper = a.copy()
a_upper[np.logical_not(idx)] = 0

a_lower = a.copy()
a_lower[idx] = 0

print a_upper
print a_lower

对于非方形矩阵的更一般情况,我不确定您希望如何放置&#34;对角线&#34;。也许像是

n, m = 3,5
a = np.arange(n*m).reshape((n,m))

idx = np.fromfunction(lambda i,j: i/(n-1.) + j/(m-1.) <= 1, (n,m))

a_upper = a.copy()
a_upper[np.logical_not(idx)] = 0

a_lower = a.copy()
a_lower[idx] = 0

print a_upper
print a_lower

是你想要的吗?

Q1 / Q3只需要在之前/之后旋转。

效率:最昂贵的部分可能是创建idx数组。但是,这可以重复使用,并且不必在每次需要分离时创建。

相关问题