2

I'm currently trying to create a legend manually for several rectangles drawn in an image. But I get confused with the coloring.

    color_step = 255/(len(contours)+1)

    patch =[]
    for cnt_idx, cnt in enumerate(contours):
        cnt_color = color_step * (cnt_idx+1)
        cv2.rectangle(img,(cnt['x'],cnt['y']), \
        (cnt['x']+cnt['w'], \
        cnt['y']+cnt['h']),cnt_color,thickness)
        
        patch.append(mpatches.Patch(color = (cnt_color/255.0,cnt_color/255.0,cnt_color/255.0 ), label='%d' %cnt_idx))

in the end I just call:

patch = np.array(patch)
plt.legend(handles=patch)
plt.imshow(img, interpolation = 'none', cmap='gray')

I found out, that the cv2.rectangle method just assigns the value defined in cnt_color at the specific location of the rectangle. Unfortunately I don't know how to define the color for the patch.

The current result: enter image description here

Community
  • 1
  • 1
Marco
  • 21
  • 3
  • Could you use a discrete colorbar as in this answer:(http://stackoverflow.com/questions/14777066/matplotlib-discrete-colorbar) instead of building the legend. – Ed Smith Aug 23 '16 at 15:10

1 Answers1

0

The problem was caused by the imshow function itself, as it normalizeses the result before showing the image. setting of vmax and vmin helped

Marco
  • 21
  • 3