how to remove grid lines on image in python? - python

I am using google colab for my project. I am getting grid lines on images even I am not writing them.
from matplotlib import pyplot as plt
%matplotlib inline
import cv2
img = cv2.imread('k15.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
for code like above, I am getting grid lines which is not the case when I run the same code in my python shell.

plt.imshow(myImage)
plt.grid(None) <---- this should remove that white grid

Apparently something in the background changes the style. I have no experience whatsoever with google colab ti judge whether this can be responsible for the observed difference in displayed image.
In any case it should be possible to manually turn the grid lines off on a per notebook basis.
%matplotlib inline
from matplotlib import pyplot as plt
plt.rcParams["axes.grid"] = False
# rest of code

If you don't mind using a different packet, you can pretty much do it easily with PIL or Pillow
from PIL import Image
img = Image.open('C:\...\k15.jpg')
img.show()

The above answer didn't work for me in an Jupyter Notebook.
Here is an alternative solution - after every imshow you need to disable the grid like this:
...
plt.imshow(image)
plt.grid(False)
...

Related

Create a Colored Image from a Gray Image

I am new here and I need some help.
I have a gray image, and I need to colour it using Python.
This is the kind of images I have:
And I need to transform it to be like the images that can be plot by using matplotlib ColorMap "CMRmap" like this one and save it:
Thank you in advance for helping me.
Sounds like you've figured out the colormap part, but not the saving. Building on Shawn's answer, if you want to save the figure, make a call to plt.savefig() instead of plt.show(). Then pass the path you want to save it to as an argument.
import cv2
import matplotlib.pyplot as plt
img = cv2.imread(r"path\to\img", 0)
plt.imshow(img, cmap='CMRmap')
plt.savefig("\path\to\output\file")
Hope this helps!
Expanding on #Miki's comment, you simply need to use a colormap. The colored image shows the CMRmap colormap.
import cv2
import matplotlib.pyplot as plt
img = cv2.imread(r"path\to\img", 0)
plt.imshow(img, cmap='CMRmap')
plt.plot()
plt.savefig('foo.png')
Output:
Matplotlib lists all the colormaps here
Edit: updated answer with OP's clarification.

Concatenated images are badly degraded

I am trying to display several pictures on my Jupyter notebook. However, the pixel is really rough like below.
The pixel of original picture is clear. How should I improve this issue ?
This is a certain point of process to have a classification whether the picture is dog or cat. I have a many pictures of dogs and cat in the folder located on same directory and just took them from there. The picture is I just tried to show on the Jupyter notebook with using matplotlib.
Thank you in advance.
To force the resolution of the matplotlib inline images:
import matplotlib as plt
dpi = 300 # Recommended to set between 150-300 for quality image preview
plt.rcParams['figure.dpi'] = dpi
I think it uses a very low setting around 80 dpi by default.
The image quality seems to be degraded in the example picture simply because you are trying to show a 64 pixel large image on 400 pixels or so on screen. Each original pixel thus comprises several pixels on screen.
It seems you do not necessarily want to use matplotlib at all if the aim is to simply show the image in its original size on screen.
%matplotlib inline
import numpy as np
from IPython import display
from PIL import Image
a = np.random.rand(64,64,3)
b = np.random.rand(64,64,3)
c = (np.concatenate((a,b), axis=1)*255).astype(np.uint8)
display.display(Image.fromarray(c))
To achieve a similar result with matplotlib, you need to crop the margin around the axes and make sure the figure size is exactly the size of the array to show.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
a = np.random.rand(64,64,3)
b = np.random.rand(64,64,3)
c = np.concatenate((a,b), axis=1)
fig, ax = plt.subplots(figsize=(c.shape[1]/100.,c.shape[0]/100.), dpi=100)
fig.subplots_adjust(0,0,1,1)
ax.axis("off")
_ = ax.imshow(c)

How can I display .png file in a the Microsoft Azure Jupyter Notebook [duplicate]

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.
I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:
gd_diagram.write("test.png", "PNG")
display(file="test.png")
However, I can't figure out how to do this - or know if it's possible. So does anyone know if images can be opened/displayed in IPython?
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
(official docs)
If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.
from IPython.display import Image, display
listOfImageNames = ['/path/to/images/1.png',
'/path/to/images/2.png']
for imageName in listOfImageNames:
display(Image(filename=imageName))
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)
from IPython.display import display
from PIL import Image
path="/path/to/image.jpg"
display(Image.open(path))
You may need to install PIL
in Anaconda this is done by typing
conda install pillow
If you want to efficiently display big number of images I recommend using IPyPlot package
import ipyplot
ipyplot.plot_images(images_array, max_images=20, img_width=150)
There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.
You could use in html code in markdown section:
example:
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
If you are looking to embed your image into ipython notebook from the local host, you can do the following:
First: find the current local path:
# show current directory
import os
cwd = os.getcwd()
cwd
The result for example would be:
'C:\\Users\\lenovo\\Tutorials'
Next, embed your image as follows:
from IPython.display import display
from PIL import Image
path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))
Make sure that you choose the right image type among jpg, jpeg or png.
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
You can directly use this instead of importing PIL
from IPython.display import Image, display
display(Image(base_image_path))
Another opt is:
from matplotlib import pyplot as plt
from io import BytesIO
from PIL import Image
import Ipython
f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()
When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.
from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))
[See Notebook]
This is the solution using opencv-python, but it opens new windows which is busy in waiting
import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()
if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()

Python OpenCV drawing errors after manipulating array with numpy

I'm reading in an image with OpenCV, and trying to do something with it in numpy (rotate 90deg). Viewing the result with imshow from matplotlib, it all seems to be working just fine - image is rotated. I can't use drawing methods from OpenCV on the new image, however. In the following code (I'm running this in a sagemath cloud worksheet):
%python
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os, sys
image = np.array( cv2.imread('imagename.png') )
plt.imshow(image,cmap='gray')
image = np.array(np.rot90(image,3) ) # put it right side up
plt.imshow(image,cmap='gray')
cv2.rectangle(image,(0,0),(100,100),(255,0,0),2)
plt.imshow(image,cmap='gray')
I get the following error on the cv2.rectangle() command:
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)
The error goes away if I use np.array(np.rot90(image,4) ) instead (i.e. rotate it 360). So it appears that the change in dimensions is messing it up. Does OpenCV store the dimensions somewhere internally that I need to update or something?
EDIT: Adding image = image.copy() after rot90() solved the problem. See rayryeng's answer below.
This is apparently a bug in the Python OpenCV wrapper. If you look at this question here: np.rot90() corrupts an opencv image, apparently doing a rotation that doesn't result back in the original dimensions corrupts the image and the OP in that post experiences the same error you are having. FWIW, I also experienced the same bug.... no idea why.
A way around this is to make a copy of the image after you rotate, and then show the image. This I can't really explain, but it seems to work. Also, make sure you call plt.show() at the end of your code to show the image:
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os, sys
image = np.array( cv2.imread('imagename.png') )
plt.imshow(image,cmap='gray')
image = np.array(np.rot90(image,3) ) # put it right side up
image = image.copy() # Change
plt.imshow(image,cmap='gray')
cv2.rectangle(image,(0,0),(100,100),(255,0,0),2)
plt.imshow(image,cmap='gray')
plt.show() # Show image
I faced the same problem with numpy 1.11.2 and opencv 3.3.0. Not sure why, but this did the job for me.
Before using cv2.rectangle, add the line below:
image1 = image1.transpose((1,0)).astype(np.uint8).copy()
Reference
Convert data type works for my problem.
The image is of type np.int64 before the convert.
image = image.astype(np.int32) # convert data type

How can I display an image from a file in Jupyter Notebook?

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.
I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:
gd_diagram.write("test.png", "PNG")
display(file="test.png")
However, I can't figure out how to do this - or know if it's possible. So does anyone know if images can be opened/displayed in IPython?
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
(official docs)
If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.
from IPython.display import Image, display
listOfImageNames = ['/path/to/images/1.png',
'/path/to/images/2.png']
for imageName in listOfImageNames:
display(Image(filename=imageName))
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)
from IPython.display import display
from PIL import Image
path="/path/to/image.jpg"
display(Image.open(path))
You may need to install PIL
in Anaconda this is done by typing
conda install pillow
If you want to efficiently display big number of images I recommend using IPyPlot package
import ipyplot
ipyplot.plot_images(images_array, max_images=20, img_width=150)
There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.
You could use in html code in markdown section:
example:
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
If you are looking to embed your image into ipython notebook from the local host, you can do the following:
First: find the current local path:
# show current directory
import os
cwd = os.getcwd()
cwd
The result for example would be:
'C:\\Users\\lenovo\\Tutorials'
Next, embed your image as follows:
from IPython.display import display
from PIL import Image
path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))
Make sure that you choose the right image type among jpg, jpeg or png.
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
You can directly use this instead of importing PIL
from IPython.display import Image, display
display(Image(base_image_path))
Another opt is:
from matplotlib import pyplot as plt
from io import BytesIO
from PIL import Image
import Ipython
f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()
When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.
from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))
[See Notebook]
This is the solution using opencv-python, but it opens new windows which is busy in waiting
import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()
if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()

Categories

Resources