I have this contour obtained with MatplotLib:
Now, I want to use it as a normal Python image (PIL or array), because I want to apply it a mask (obtained with OpenCV).
The problem is that with MatplotLib, the image with the contour is resized, and a margin is added (for the axis, even if I don't draw the axis), so the image that I obtain from the figure of MatplotLib doesn't fit with the mask obtained with OpenCV.
I tried to get the same contour with OpenCV, but I don't obtain any result with the cv2.FindContours and cv2.DrawContours functions (if you know how to do it this way, please tell me... in this previous topic you can see the original image and the contour that I want )
Another possible solution would be to convert the contour obtained with the MatplotLib to an image (PIL or array) with the same size as the original, and without margins.
I hope you could help me at least with one of these solutions!
--------------------------- EDIT ---------------------------
Rutger Kassies' answer is right. It wasn't working 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 must be before using the contour function. Keep that in mind!
I once posted the question how you could plot an image with .imshow and save it again so it would equal the input image. The respons i got might be helpfull in your case, this is how you can save the contour'ed image 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With