Convert the outline (MatplotLib or OpenCV) to an image of the same size as the original

I have this circuit obtained using MatplotLib:

Contour

Now I want to use it as a regular Python image (PIL or array), because I want to apply it to a mask (obtained using OpenCV).

The problem is that with MatplotLib the image with the outline changes and an edge is added (for the axis, even if I don’t draw the axis), so the image that I get from the MatplotLib figure does not match the mask obtained with OpenCV.

I tried to get the same outline with OpenCV, but I don't get any result with the functions cv2.FindContours and cv2.DrawContours (if you know how to do this, please tell me ... in this previous topic you can see the original image and the outline that I want)

Another possible solution would be to convert the outline obtained with MatplotLib into an image (PIL or array) with the same size as the original and without borders.

I hope you could help me with at least one of these solutions!

--------------------------- EDIT ------------------- --- -----

Answer Rutger Kassies is right. This did not work for me because I wrote this line ...

ax = plt.axes([0, 0, 1, 1], frame_on=False, xticks=[], yticks=[]) 

... after using the contour function, and it should be before using the contour function. Remember this!

+7
source share
1 answer

I once posted a question about how you could draw an image using .imshow and save it again so that it matches the input image. The answer I received may be useful in your case, so you can save the image with the outline with the same dimensions:

 from PIL import Image im = np.array(Image.open('input_image.jpg').convert('L')) xpixels = im.shape[1] ypixels = im.shape[0] dpi = 72 scalefactor = 1 xinch = xpixels * scalefactor / dpi yinch = ypixels * scalefactor / dpi fig = plt.figure(figsize=(xinch,yinch)) ax = plt.axes([0, 0, 1, 1], frame_on=False, xticks=[], yticks=[]) contour(im, levels=[240], colors='black', origin='image') plt.savefig('same_size.png', dpi=dpi) 
+4
source

All Articles