1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import numpy as np import matplotlib.pyplot as plt import os import pylab as plot
params = {'legend.fontsize': 12, 'legend.handlelength': 2} plot.rcParams.update(params) from matplotlib.patches import Rectangle
RESULT_DIR = "./result" if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR, exist_ok=True)
for png_name in os.listdir("./data"): no_color_img = plt.imread(os.path.join("./data", png_name)) unique_value = np.unique(no_color_img, return_counts=True)[0] print("total_color_count:", len(unique_value)) value_list = sorted(unique_value.tolist()) new_color_img = np.zeros_like(no_color_img) for index, pvalue in enumerate(value_list): new_color_img[no_color_img == pvalue] = index print(value_list)
fig, ax = plt.subplots(1, 2) img_ax = ax[0] imgs = img_ax.imshow(new_color_img, cmap=plt.get_cmap("winter", len(value_list))) img_ax.axis("off")
legend_ax = ax[1] if len(value_list) == 2: legend_data = [[0, [16, 255, 127], "Ferrite"], [1, [0, 5, 255], "Martensite"]] elif len(value_list) == 3: legend_data = [[0, [16, 255, 127], "Ferrite"], [1, [0, 5, 255], "Martensite"],[2, [0, 5, 255], "Martensite"]]
handles = [ Rectangle((0, 0), 1, 1, color=[v / 255 for v in c]) for k, c, n in legend_data ] legend_ax.legend(handles, [n for k, c, n in legend_data], mode="expand", ncol=1, frameon=False, loc="center") legend_ax.axis("off") plt.subplots_adjust(hspace=0, wspace=0) plt.savefig(os.path.join(RESULT_DIR, "{}-color.tiff".format(png_name)), dpi=1200, bbox_inches='tight', format="tiff", transparent=True, pil_kwargs={"compression": "tiff_deflate"}) plt.show()
|