[OpenCV implements images: OpenCV uses Python to create heat maps]

overview

Heat map is a powerful statistical chart that visually displays the heat and density of data distribution by color mapping the data. When drawing a heat map, the key is to specify the rules for color mapping, which determine how different values ​​are represented in the graph. Typically, larger values ​​are represented in darker or warmer colors, while smaller values ​​are presented in lighter or cooler colors, allowing observers to quickly understand the relative magnitude and trends of the data.

read image

First, let's read the sample image and perform the corresponding crop operation on it.
The sample code is as follows:


import numpy as np
import matplotlib.pyplot as plt
import skimage.io as io
img = plt.imread("img_2.png")
# crop
img_cut = img[0:400,:,:]
plt.figure()
plt.imshow(img_cut)
plt.show()

Insert image description here

Image grayscale

Since heat maps are mainly used to visualize two-dimensional matrices, we need to convert the color image into a grayscale image. The code is as follows:


import numpy as np
import matplotlib.pyplot as plt
import skimage.io as io
img = plt.imread("img_2.png")
# crop
img_cut = img[0:400,:,:]
plt.figure()
plt.imshow(img_cut)
plt.show()
from skimage.color import rgb2gray
gray_img = rgb2gray(img_cut)
plt.imshow(gray_img,cmap='gray')
plt.show()

Insert image description here

pixelation effect

The pixelation effect is an image processing technique designed to give images an artistic, pixelated look. The key step in this operation is to divide the image into non-overlapping blocks, the size of which determines the granularity of the final pixelation effect. Generally, the larger the block size, the more the image looks like it's made up of blocks of pixels.

from PIL import Image


def pixelate(image_path, pixel_size):
    # 打开图片
    img = Image.open(image_path)

    # 获取图片的宽度和高度
    width, height = img.size

    # 计算每个像素块的大小
    pixel_size = max(1, pixel_size)
    block_size = (width // pixel_size, height // pixel_size)

    # 缩小图像,然后放大回原始大小,实现像素化效果
    img = img.resize(block_size, resample=Image.NEAREST)
    img = img.resize((width, height), resample=Image.NEAREST)

    # 保存处理后的图像
    output_path = "pixelated_" + str(pixel_size) + "_" + image_path
    img.save(output_path)


# 使用例子
image_path = "img_2.png"
pixel_size = 10
pixelate(image_path, pixel_size)

Insert image description here

Heat map drawing

After processing the grayscale image and pixelation, we will further draw the heat map. Heat map is a way to display the distribution of data through color mapping. We will use the Seaborn library to draw the heat map and use the pixel blocks of the image as data points.

First, we need to install the Seaborn library, you can use the following command:

pip install seaborn

Next, we will use the processed grayscale image to draw a heat map:

import seaborn as sns
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

def heatmap_from_image(image_path, pixel_size):
    # 打开处理后的图片
    img = Image.open("pixelated_" + str(pixel_size) + "_" + image_path)

    # 将图像转为NumPy数组
    img_array = np.array(img)

    # 创建热力图
    plt.figure(figsize=(10, 8))
    sns.heatmap(img_array[:, :, 0], cmap="viridis", cbar=False)

    # 设置图像标题和坐标轴标签
    plt.title("Heatmap from Pixelated Image")
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis")

    # 显示热力图
    plt.show()

# 使用例子
heatmap_from_image("img_2.png", 10)

This code converts the pixelated image into a NumPy array and draws the heatmap using the Seaborn library. We use the viridis colormap, you can choose other colormaps if needed.

Heat map palette

The Seaborn library provides rich color palette options that allow you to customize the color style of your heat map. In the above code, we used the viridis palette, if you want to try other palettes, just modify the cmap parameters. For example, if we change the "cmap" parameter in the code to "coolwarm", the effect is as follows:

import seaborn as sns
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

def heatmap_with_custom_palette(image_path, pixel_size, palette_name):
    # 打开处理后的图片
    img = Image.open("pixelated_" + str(pixel_size) + "_" + image_path)

    # 将图像转为NumPy数组
    img_array = np.array(img)

    # 创建热力图
    plt.figure(figsize=(10, 8))
    sns.heatmap(img_array[:, :, 0], cmap=palette_name, cbar=False)

    # 设置图像标题和坐标轴标签
    plt.title(f"Heatmap with {palette_name} Palette")
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis")

    # 显示热力图
    plt.show()

# 使用例子
heatmap_with_custom_palette("img_2.png", 10, "coolwarm")

By modifying the palette_name parameter, you can use different palettes supported by Seaborn, such as "coolwarm", "viridis", etc.

summary

Heat map is a powerful data visualization tool that visually displays the distribution and density of data through color mapping. When creating heat maps, we prepare a suitable foundation for the data through image processing, including image cropping, grayscale, and pixelation. By combining image processing and data visualization methods, the characteristics of the data can be presented more vividly, making analysis and understanding more intuitive. This process is not only applicable to image data, but can also be used to draw heat maps of other two-dimensional data, providing more possibilities for data analysis.

Guess you like

Origin blog.csdn.net/weixin_47869094/article/details/134469453