我建议您安装并使用OpenCV 来帮助处理。这也提供了一个可以使用的 Python 库。
以下适用于您提供的热图。您需要针对大量热图进行相应修改。
它首先将图像裁剪成 3 个图像,分别用于 A、B 和 C。接下来,它提取每个类别颜色的像素,首先将它们转换为白色,然后将每个像素调整为16 x 16 灰度图像。接下来,它将非零值转换为当前类别值并将其添加到您的数组中。
import numpy as np
import cv2
def parse_image(img):
# Start with all zeros in a 16x16 array
data = np.zeros((16, 16), dtype=int)
# List holding min and max BGR values for each category
categories = [
(5, (0, 0, 250), (5, 5, 255)), # Red
(4, (5, 60, 152), (12, 78, 160)), # Dark brown
(3, (9, 105, 225), (18, 120, 240)), # Light brown
(2, (220, 235, 250), (230, 245, 255)), # Light orange
(1, (250, 250, 250), (255, 255, 255)), # White
]
for category, bgr_min, bgr_max in categories:
# Extract pixels in the required range and convert them to 255
mask = cv2.inRange(img, bgr_min, bgr_max)
image_cat = cv2.bitwise_or(img, np.full(img.shape, 255, dtype=np.uint8), mask=mask)
# Convert the image into greyscale
image_grey = cv2.cvtColor(image_cat, cv2.COLOR_BGR2GRAY)
# Resize the image to 16x16
values = cv2.resize(image_grey, (16, 16))
# Convert non black values into the current category value
values[values > 0] = category
# Add the values to the data array
data = data + values
return data
# Load the heatmap
image_src = cv2.imread("heatmap.jpg")
cv2.imshow("Source", image_src)
# Crop into 3 sub images
starty = 28
cropx = 234
cropy = 184
images = []
for number, startx in enumerate([30, 303, 572], start=1):
images.append(image_src[starty:starty+cropy,startx:startx+cropx])
# Parse A, B and C
abc = [parse_image(img) for img in images]
print abc
因此,对于您提供的热图,您将获得以下输出(可以重新调整为单个数组):
[array([[2, 2, 5, 3, 5, 3, 5, 4, 2, 5, 2, 2, 5, 2, 2, 2],
[2, 2, 2, 3, 2, 2, 4, 3, 2, 4, 2, 2, 5, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 3, 2, 3, 3, 2, 2, 5, 2, 2, 2],
[4, 3, 2, 5, 4, 2, 5, 5, 5, 5, 2, 2, 5,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, 2, 2, 2, 2, 2, 3, 3, 2],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2]])]
请注意,使用 JPG 图像意味着图像中会有伪影,因此颜色不会有准确的值。这就是为什么有最小值和最大值。通常你也会看到RGB 值。但在这里,您将使用 BGR 值。您将需要调整最小最大值以确保您不会获得任何 0 值。