NameError: name 'display' is not defined - python

I try to run python code using Linux terminal to display a png image.but it gives me same error again and again.
from PIL import Image
im=Image.open("/content/sample_1.png")
# Lets display the image
display(im)

You could try using im.show() instead of display():
from PIL import Image
im=Image.open("/content/sample_1.png")
# Lets display the image
im.show()

display is a command on the Linux shell, and you can't use in python directly.
If you just want to show the PNG image, you can use the following code:
import subprocess
im="/content/sample_1.png"
subprocess.getoutput("display %s" %im)

Related

Image.show() doesn't display image

I am trying to display an image on VScode using Image.show from the pillow library but it doesn't work.
This is the code:
from PIL import Image
im = Image.open("/workspaces/105456256/project/before2.jpg")
im.show()
when I run this I don't get any error, instead, nothing happens.
My OS is Windows 11.
I tried the same code on PyCharm and it worked just fine.
Try using:
from PIL import Image
im = Image.open("/workspaces/105456256/project/before2.jpg")
im.show()
input("Press ENTER to exit") # pause

cv2.error: OpenCV(4.5.2) .error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

import cv2 #for image processing
import easygui #to open the filebox
import numpy as np #to store image
import imageio #to read image stored at particular path
import sys
import matplotlib.pyplot as plt
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
top=tk.Tk()
top.geometry('400x400')
top.title('Cartoonify Your Image !')
top.configure(background='white')
label=Label(top,background='#CDCDCD', font=('calibri',20,'bold'))
def upload():
ImagePath=easygui.fileopenbox()
cartoonify(ImagePath)
def cartoonify(ImagePath):
# read the image
originalmage = cv2.imread(ImagePath)
originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB)
#print(image) # image is stored in form of numbers
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-vi271kac\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Check the image address again. This usually happens when the image is not loaded correctly in any way. Try giving the address directly; something like "C:\\test.jpg"
import cv2
im = cv2.imread("WRONG IMAGE ADDRESS.jpg", 1)
im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
Update
You can also get the current folder path of your script and load your image from that.
Imagine your files structure are like this:
--RootProject
|-img.jpg
|-script.py
Then you can also do something like this:
script.py
import cv2
import sys
im = cv2.imread(sys.path[0]+"/img.jpg", 1)
im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
Try giving the image as a path, and one thing to be careful is about the slashes. Use \\ instead of \. Your path must look like D:\\file\\file1\\file2.
To check if it worker print type(cv2.imread(path)). If it prints <class 'numpy.ndarray'>, then you are good to go.
This may happen if your image file path is wrong, add your working folder then use as below:
image = cv2.imread('eye_face.jpg')
type(image)
then your image type will indicate as numpy.ndarray, if your image file path is wrong then the type will be NoneType.
This error is {wrong image location}. If suppose your image in another folder means use like this:
img=cv2.imread("../images/car.jpg",1)
This seems to be the path issue in windows. I changed it to a full path like this and it worked.
filename = "D:\Sandbox\Github\opencv-project\Resources\Photos\cats.jpg"
I was trying to read images from a folder and having the same trouble. I had a non-image in one of the folders that was the problem.
I solved the same problem by adding:
data = cv2.imread('path_to_your_image', as_grey =True)
and then try to also add the flags = cv2.DFT_COMPLEX_OUTPUT to this line
dft = cv2.dft(np.float32('your_image'),flags = cv2.DFT_COMPLEX_OUTPUT)
there are many solutions for this issue out there.
This might be because of your camera issue or the camera driver issue. If you are using any USB camera then cross-check its connection and ensure that no other programs are using the same camera.
If your camera is working then you might put the wrong image path. Verify the image path. Also, try to put a hardcoded path like C:\\image1.png if needed.
import cv2
im = cv2.imread("C:\\image1.png", 1)
im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
Please check the extension you give to the path. JPEG,PNG or anything else.
Check if your camera has been disabled in the device manager, or else upadate it.

How to display Images loaded with Pillow with Pygame in Python 3.7?

I imported an image to my project using
from PIL import Image
myImage = Image.open("myImageDirectory.png")
So myImage is now imported as a png file. But I want to display it to the Screen using Pygame. Normally I use
import pygame
win = pygame.display.set_mode((500, 500))
win.blit(myImage, (50, 50))
Now I get the Error that the function needs a surface, not a png File.
Has anyone an idea how I can convert the image to a surface or how I can display it?
I tried not much yet​ because I didn't found anything that could solve my problem.
Edit:
What is wrong with this way that I get the error: Couldn't open bg.png
See PIL and pygame.image. Use Image.tobytes() get the image data as a bytes object and pygame.image.fromstring() to load the data to an pygame.Surface object:
from PIL import Image
import pygame
pilImage = Image.open("myImageDirectory.png")
myImage = pygame.image.fromstring(pilImage.tobytes(), pilImage.size, pilImage.mode)

Taking Screen shots of specific size

What imaging modules for python will allow you to take a specific size screenshot (not whole screen)?
I have tried PIL, but can't seem to make ImageGrab.grab() select a small rectangle
and i have tried PyGame but i can't make it take a screen shot outside of it's main display panel
You can use pyscreenshot module.
The pyscreenshot module can be used to copy the contents of the screen to a PIL image memory or file.
You can install it using pip.
$ sudo pip install pyscreenshot
Usage:
import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
I have tried PIL, but can't seem to make ImageGrab.grab() select a small rectangle
What did you try?
As the documentation for ImageGrab clearly states, the function has a bbox parameter, and:
The pixels inside the bounding box are returned as an “RGB” image. If the bounding box is omitted, the entire screen is copied.
So, you only get the whole screen if you don't pass a bbox.
Note that, although I linked to the Pillow docs (and you should be using Pillow), old-school PIL's docs say the same thing:
The bounding box argument can be used to copy only a part of the screen.
So, unless you're using a really, really old version of PIL (before 1.1.3, which I believe is more than a decade out of date), it has this feature.
1) Use pyscreenshot, ImageGrab works but only on Windows
2) Grab the image and box it, then save that image
3) Don't use ImageGrab.grab_to_file, it saves the full size image
4) You don't need to show the image with im.show if you just want to save a screenshot
import pyscreenshot as ImageGrab
im=ImageGrab.grab(bbox=(10,10,500,500))
im.save('im.png')
You could use Python MSS.
From documentation to capture only a part of the screen:
import mss
import mss.tools
with mss.mss() as sct:
# The screen part to capture
monitor = {"top": 160, "left": 160, "width": 160, "height": 135}
output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor)
# Grab the data
sct_img = sct.grab(monitor)
# Save to the picture file
mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
print(output)
You can use pyscreenshot at linux or windows platforms . I am using Ubuntu it works for me. You can force if subprocess is applied setting it to false together with mss gives the best performance.
import pyscreenshot as ImageGrab
import time
t1 = time.time()
imgScreen = ImageGrab.grab(backend="mss", childprocess=False)
img = imgScreen.resize((640,480))
img.save("screen.png")
t2 = time.time()
print("The passing time",(t2-t1))

How to show PIL images on the screen?

I am doing some image editing with the PIL libary. The point is, that I don't want to save the image each time on my HDD to view it in Explorer. Is there a small module that simply enables me to set up a window and display the image?
From near the beginning of the PIL Tutorial:
Once you have an instance of the Image class, you can use the methods
defined by this class to process and manipulate the image. For
example, let's display the image we just loaded:
     >>> im.show()
Update:
Nowadays the Image.show() method is formally documented in the Pillow fork of PIL along with an explanation of how it's implemented on different OSs.
I tested this and it works fine for me:
from PIL import Image
im = Image.open('image.jpg')
im.show()
You can use pyplot to show images:
from PIL import Image
import matplotlib.pyplot as plt
im = Image.open('image.jpg')
plt.imshow(im)
plt.show() # image will not be displayed without this
If you find that PIL has problems on some platforms, using a native image viewer may help.
img.save("tmp.png") #Save the image to a PNG file called tmp.png.
For MacOS:
import os
os.system("open tmp.png") #Will open in Preview.
For most GNU/Linux systems with X.Org and a desktop environment:
import os
os.system("xdg-open tmp.png")
For Windows:
import os
os.system("powershell -c tmp.png")
Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:
http://matplotlib.org/users/image_tutorial.html
You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
For Python 3, replace import Tkinter as tk with import tkinter as tk.
Yes, PIL.Image.Image.show() easy and convenient.
But if you want to put the image together, and do some comparing, then I will suggest you use the matplotlib. Below is an example,
import PIL
import PIL.IcoImagePlugin
import PIL.Image
import matplotlib.pyplot as plt
with PIL.Image.open("favicon.ico") as pil_img:
pil_img: PIL.IcoImagePlugin.IcoImageFile # You can omit. It helps IDE know what the object is, and then it will hint at the method very correctly.
out_img = pil_img.resize((48, 48), PIL.Image.ANTIALIAS)
plt.figure(figsize=(2, 1)) # 2 row and 1 column.
plt.subplots_adjust(hspace=1) # or you can try: plt.tight_layout()
plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0)) # set xtick, ytick to transparent
plt.subplot(2, 1, 1), plt.imshow(pil_img)
plt.subplot(2, 1, 2), plt.imshow(out_img)
plt.show()
This is what worked for me:
roses = list(data_dir.glob('roses/*'))
abc = PIL.Image.open(str(roses[0]))
PIL.Image._show(abc)

Categories

Resources