Image not Displaying even after following effbot [duplicate] - python-3.x

This question already has an answer here:
PhotoImage not showing up the image associated with it
(1 answer)
Closed 3 years ago.
I'm trying to add in an image to a screen and its not displaying.
Followed other Stack overflow solutions and the Effbot solution and neither worked. Ive moved the image around and it still isnt displaying so its not where its displaying. Not getting any Error messages either.
image = PhotoImage("newspaper-extra-computer-icons-breaking-newsnewspaper.jpg")
image_label = Label(news_aggregator,image = image)
image_label.image = image
image_label.place(x=400,y = 200)
Just expecting the image to be displayed.

The main problem is you are missing file= in PhotoImage().
Try this:
PhotoImage(file='path_to_image.gif')
That said tkinter only supports a hand full of formats.
The PhotoImage class can read GIF and PGM/PPM images from files
For working with other formats you will need PIL.
If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:
You can see all there here on the documentation.
For your file try this:
import tkinter as tk
from PIL import ImageTk
root = tk.Tk()
image = ImageTk.PhotoImage(file="newspaper-extra-computer-icons-breaking-newsnewspaper.jpg")
image_label = tk.Label(root, image=image)
image_label.image = image
image_label.place(x=400, y=200)
root.mainloop()
Keep in mind due to you using place() the above code will not be showing the image as it is off frame. You will need to expand the window.

Related

PhotoImage does not recognize PNG image - Keep getting following error: _tkinter.TclError: couldn't recognize data in image file "MyImage.png"

I'm currently learning Tkinter, and I wanted to add a PNG image to my Tkinter Canvas object. The code is shown below.
window = Tk()
window.title('My Title')
canvas = Canvas(width=200, height=200)
canvas.pack()
img = PhotoImage(file='MyImage.png')
canvas.create_image(100, 100, image=img)
window.mainloop()
Seems simple enough, but I keep getting the following error: _tkinter.TclError: couldn't recognize data in image file "MyImage.png"
I read that PhotoImage will return this error if you try to read a .jpg file, however, it should work with PNG files. I've also tried out PIL, but that came with a whole bunch of other issues. Any suggestions?

cv2.cvtColor(img,cv2.COLOR_BGR2RGB) not working

I am trying to create a screen recorder using mss and Opencv in python, the video I am capturing has a very different colours than original computer screen. I tried to find the solution online, Everyone saying it should be fixed using cvtColor() but I already have it in my code.
import cv2
from PIL import Image
import numpy as np
from mss import mss
import threading
from datetime import datetime
`
def thread_recording():
fourcc=cv2.VideoWriter_fourcc(*'mp4v')
#fourcc=cv2.VideoWriter_fourcc(*'XVID')
out=cv2.VideoWriter(vid_file,fourcc,50,(width,height))
mon = {"top": 0, "left": 0, "width":width, "height":height}
sct = mss()
thread1=threading.Thread(target=record,args=(mon,out,sct))
thread1.start()
def record(mon,out,sct):
global recording
recording=True
while recording:
frame= np.array(sct.grab(mon))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
out.release()
the vid_file variable contains a string of output file name with mp4 extension
Screenshot of my screen
Screenshot from recorded video
So, I looked around some more and found that apparently this is a bug in opencv for versions 3.x on wards.then I tried PIL for getting rgb image and removed cvtColor(),but it produced an empty video.I removed both cvtColor() as well as PIL Image as suggested by #ZdaR it again wrote empty video Hence I had to put it back and boom. even if cvtColor() seems like doing nothing, for some unknown reason it has to be there.when you use PIL Image along with cvtColor() it writes the video as expected
from PIL import Image
def record(mon,out,sct):
global recording
recording=True
while recording:
frame=sct.grab(mon)
frame = Image.frombytes('RGB', frame.size, frame.rgb)
frame = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2RGB)
out.write(np.array(frame))
out.release()
as I am very new to programming, I would really appreciate your help if I missed or overlooked something important
You can do
frameRGB = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
Frame is in BGR, and it will work the same as you are only changing R with B where frameRGB is in RGB now. This command will transfer R to B and works to transfer frames from RGB and BGR as well as BGR to RGB. BGR2RGB might be a bug, I have it as well but the command I mentioned works perfectly. That's what I do.
MSS store raw BGRA pixels. Does it work if you change to:
# Grab it
img = np.array(sct.grab(mon))
# Convert from BGRA to RGB
frame = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
you should run this command in cmd
pip install opencv-python

How do i close a figure shown using matplotlib in python ? And What is difference among image, figure and picture?

I am using ubuntu. I want to close a figure shown using matplotlib after few seconds without using keyboard or mouse. I am able to close an image shown using PIL after few seconds by getting its process id and then kill it.
And i am also little bit confused among terms figure, image and picture in matplotlib.
Thank you so much in advance.
Regarding part 1.
i have used plt.close(), plt.close("all") as well as 'psutil' library to fetch process ID and kill. But none of them worked. I got only solution of closing an image opened via 'PIL'.
link :-
How can I close an image shown to the user with the Python Imaging Library?
Regarding part 2.
Actually, at some pages, i found the terms 'figure','picture' and 'image' were used interchangeably; and at some pages they were not. I saw 'plt.imshow()' is used for image and picture and 'plt.show()' is used for figure. But, what is difference between figure, image and picture. And when to use these functions?
link :-
Why plt.imshow() doesn't display the image?
# for graphing
import matplotlib.pyplot as plt
import time
# for process
import psutil
# importing for image processing
from PIL import Image
#### closing an image which was opened via PIL
#### working perfectly
filename = "check.jpg"
img = Image.open(filename)
img.show()
time.sleep(5)
# for killing process such that image viewer
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
#### closing an image/figure which was opened via matplotlib
#### unable to close without keyboard or mouse
x = [[1,2,3,4],[11,22,33,44],[9,8,7,6]]
print (x)
plt.imshow(x)
plt.colorbar()
plt.title("a")
plt.xlabel('b')
plt.ylabel('c')
a = plt.show()
time.sleep(2)
## not working
plt.close()
## not working
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
## not working
plt.close("all")
i expect that my shown figure closes automatically after a few seconds,
instead of any manual intervention.

How to overlay images on each other in python and opencv?

I am trying to write images over each other. Ideally, what I want to do is to write every image in one folder over every image in another folder and output every unique image to another folder. So far, I am just working on having one image write over one image, but I can't seem to get that to work.
import numpy as np
import cv2
import matplotlib
def opencv_createsamples():
mask = ('resized_pos/2')
img = cv2.imread('neg/1')
new_img = img * (mask.astype(img.dtype))
cv2.imwrite('samp', new_img)
opencv_createsamples()
It would be helpful to have more information about your errors.
Something that stands out immediately is the lack of file type extensions. Your images are probably not being read correctly, to begin with. Also, image sizes would be a good thing to consider so you could resize as required.
If the goal is to blend images, considering the alpha channel is important. Here is a relevant question on StackOverflow:How to overlay images in python
Some other OpenCV docs that have helped me in the past: https://docs.opencv.org/trunk/d0/d86/tutorial_py_image_arithmetics.html
https://docs.opencv.org/3.1.0/d5/dc4/tutorial_adding_images.html
Hope this helps!

Tkinter best button text flipping method

So I'm working on a tkinter project and one issue I come across is finding a way to flip/rotate a button object's text vertically. One way I can kinda cheat into making this happen is putting a canvas object on top of the button with the canvas being drawn last (as shown below) but is there a cleaner way to approach this by just manipulating the Button object attributes?
from tkinter import*
root = Tk()
windowDimensions = (1300,600)
root.title("Mapper")
root.geometry(str(windowDimensions[0])+"x"+str(windowDimensions[1]))
button1=Button(root,text='',width=2,height=9)
button1.place(x=0,y=20)
can = Canvas(root,width=15,height=80)
can.place(x=2,y=30)
can.create_text(0, 80, anchor="nw", angle=90,text='hello',font=("Purisa", 12))
root.mainloop()
Edit: A problem I get with doing it this way is any place where the canvas is on the button, it obstructs the ability to click where the canvas is.
Your best option (which isn't a great option) is to screenshot the button, rotate it in an image editor, and then use that image in your button instead of text.
from tkinter import*
root = Tk()
# .gif file encoded as base64
vert_button_data = '''
R0lGODlhDQBCAKUkAAAAAAAANgAAYDYAADYANjYAYGAAAGAANmAAYAA2hzY2h4c2AGA2h4c2NgBg
qzZghzZgq2BgNqtgAKtgNjaHhzaHzmCHh6uHNs6HNmCr8PCrYIfOq4fO8PDOh6vwq6vw8M7w8PDw
q/DwzvDw8P//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////ywAAAAADQBCAAAG/sCRcEgsGo+cpFJJ
PDgPAWeUGKpSMFUM5Qggdo2DDAiU+RY7BoXCoDmOQp1OqLisN5/4A7XqqfqPAm5EERVLRwcGeEd+
f0gZGR9uGQQSEgUcXB1CHQFcXkdhHx8ZA0doBQUGmotxc0QOhZFuGhgNCLAcskUiIbQNAg5HHxwV
DwYSRMQQCBMYckUHAxYbIG5wtQwOGRzVRrwaFwEJRiAcGQ4KCxhE5woNEhodIkXw8oL3+Pn35pCS
lJaYjABYxcnTEDNEQo0qZeRUqlVG4DxLVofJkDyKhjDaSLFiQCEYn+zZWEVYhWAjUBYRoOELwoMj
XILiAOBDBYZnoj201oqOIMePI/BEEanRDwBGbl4avKdUyBIAhi4+SURUCMlG+oIAADs=
'''
windowDimensions = (1300,600)
root.title("Mapper")
root.geometry("{}x{}".format(*windowDimensions))
button1_image = PhotoImage(data=vert_button_data)
button1=Button(root,image=button1_image)
button1.place(x=0,y=20)
root.mainloop()
You'll lose the hover animation but again that's something you can recreate with images.
To get the base64 encoded data from a .gif you can use this:
import codecs
with open('export.gif', 'rb') as f:
print(codecs.encode(f.read(), 'base64').decode())

Resources