def load_image_by_index(i):
image_path = paintings_links.iloc[i].img_path
img = cv2.imdecode(np.fromfile(str(Path.cwd()/image_path), np.uint8), cv2.IMREAD_UNCHANGED)
return img
def get_hist_data_by_index(img_index):
bin_div = 5
img = load_image_by_index(img_index)
b, bins= np.histogram(img[:,:,0], bins=255//bin_div, range=(0,255), density=True)
g = np.histogram(img[:,:,1], bins=255//bin_div, range=(0,255), density=True)[0]
r = np.histogram(img[:,:,2], bins=255//bin_div, range=(0,255), density=True)[0]
return bins, r, g, b
def plot_image_with_hist_by_index(img_index, height=6):
bins, r, g, b = get_hist_data_by_index(img_index)
img = load_image_by_index(img_index)
fig = plt.figure(constrained_layout=True)
if img.shape[0] < img.shape[1]:
width_ratios = [3,1]
else:
width_ratios = [1,1]
gs = GridSpec(3, 2, figure=fig,
width_ratios = [3,1]
)
ax_img = fig.add_subplot(gs[:,0])
ax_r = fig.add_subplot(gs[0, 1])
ax_g = fig.add_subplot(gs[1, 1], sharey=ax_r)
ax_b = fig.add_subplot(gs[2, 1], sharey=ax_r)
ax_img.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB),aspect = 'equal')
ax_img.axis('off')
ax_r.bar(bins[:-1], r, width = 5, color='red',alpha=0.7)
ax_g.bar(bins[:-1], g, width = 5, color='green',alpha=0.7)
ax_b.bar(bins[:-1], b, width = 5, color='blue',alpha=0.7)
ax_r.axes.get_xaxis().set_ticks([])
ax_r.axes.get_yaxis().set_ticks([])
ax_g.axes.get_xaxis().set_ticks([])
ax_g.axes.get_yaxis().set_ticks([])
ax_b.axes.get_xaxis().set_ticks([])
ax_b.axes.get_yaxis().set_ticks([])
fig.suptitle("{} - {}".format(paintings_links.iloc[img_index].artist_name,
paintings_links.iloc[img_index].picture_name),ha= "left")
fig.set_figheight(height)
plt.axis('tight')
if img.shape[0] < img.shape[1]:
fig.set_figwidth(img.shape[1] *height / img.shape[0] *1.25)
else:
fig.set_figwidth(img.shape[1] *height / img.shape[0] *1.5)
plt.show()