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

Python - Get average RGB Components of Image Regions

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

图像被分成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)]

对于正方形 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

对于非方矩阵的更一般情况,我不确定您想如何放置 "diagonal"。也许像

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 只需旋转 before/after。

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