Python 3.7, tkinter, jpg: couldn't recognize data in image file - python-3.x

I wanted to ask some help regarding tkinter, in python3.
I can't seem to display a jpeg image file in a label using the following code:
def changephoto(self):
self.tmpimgpath = filedialog.askopenfilename(initialdir=os.getcwd())
self.installimagepath.set(self.tmpimgpath)
self.selectedpicture = PhotoImage(file=self.installimagepath.get())
self.PictureLabel.configure(image=self.selectedpicture)
It can do png Images just fine, but when I try to load a jpg image, all I i am able to get is the following error:
_tkinter.TclError: couldn't recognize data in image file
I went through all similar questions I could find, but they all seem to answer the same thing: "from PIL import ImageTk, Image"
When I try that ( for the moment, I am trying to use pillow, btw ), ImageTk doesn't seem to be available.
Any help would be greatly appreciated.

You have to install PIL: pip install pillow.
If pip does not successfully install pillow, you might have to try pip3 or pip3.7 (use bash to see which options you have)
You can open your image with ImageTk:
import os
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk
def changephoto():
root = tk.Tk()
PictureLabel= tk.Label(root)
PictureLabel.pack()
tmpimgpath = filedialog.askopenfilename(initialdir=os.getcwd())
selectedpicture= ImageTk.PhotoImage(file=tmpimgpath)
PictureLabel.configure(image=selectedpicture)

Solution provided by Chuck G worked. I can't tell why I initially couldn't import ImageTk, but that ended up to just work.
from PIL import ImageTk

This error could possibly happen because of relative file path or non-English characters in filepath ,So i made this function which works very good in windows and with any kinds of file paths :
def loadrelimages(relativepath):
from PIL import ImageTk, Image
import os
directory_path = os.path.dirname(__file__)
file_path = os.path.join(directory_path, relativepath)
img = ImageTk.PhotoImage(Image.open(file_path.replace('\\',"/")))
return img
for example load photo_2021-08-16_18-44-28.jpg which is at the same directory with this code:
from tkinter import *
import os
def loadrelimages(relativepath):
from PIL import ImageTk, Image
import os
directory_path = os.path.dirname(__file__)
file_path = os.path.join(directory_path, relativepath)
img = ImageTk.PhotoImage(Image.open(file_path.replace('\\',"/")))
return img
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()
loadedimage=loadrelimages('photo_2021-08-16_18-44-28.jpg')
canvas.create_image(250, 250, image=loadedimage)
root.mainloop()
try this!!!!

Related

Is there a way to use the ffmpeg binary/unix executable in a py2app application to run ffmpeg on computers without it installed?

I wrote a small python script that is essentially just a text to speech script. It uses the pydub - audiosegment python library to convert the mp3 from gTTS to an ogg that can be played in pygame. A link to my github repository can be found here: https://github.com/AnupPlays/TTS
this is the main function:
def webscrape():
global x
global b
b.state(['disabled'])
src = "sound.mp3"
dst = "sound.ogg"
murl = str(url.get())
response = requests.get(murl)
response.raise_for_status()
parse = bs4.BeautifulSoup(response.text, 'html.parser')
x = str(parse.get_text())
print(x)
text = gTTS(x)
text.save("sound.mp3")
AudioSegment.from_mp3(src).export(dst, format='ogg')
b.state(['!disabled'])
this is a list of my imports:
#Imports
import os
import sys
import pygame
#google text to speech
from gtts import gTTS
#requests and BeautifulSoup
import requests
import bs4
#pygame audio player
from pygame import mixer
#tkinter ui
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
#mp3 -> wav
from os import path
from pydub import AudioSegment
For anyone wondering using homebrew you can get the dependencies for this and copy those dependencies into your packager.

Getting this black window instead of picture while using cv2.imshow

I don't know what term I should use for the window I am getting so I am attaching a screenshot of the window for reference.
I am getting this window about 7 of the 10 times I am running this code:
import cv2
import numpy as np
import face_recognition
imgElon = face_recognition.load_image_file("BasicFaceRecImg/ElonMusk2.jpg")
imgElon = cv2.cvtColor(imgElon, cv2.COLOR_BGR2RGB)
imgElon_face_loc = face_recognition.face_locations(imgElon)[0]
print(imgElon_face_loc)
imgElon_encode = face_recognition.face_encodings(imgElon)[0]
cv2.rectangle(imgElon, (imgElon_face_loc[0], imgElon_face_loc[3]), (imgElon_face_loc[1], imgElon_face_loc[2]),(255, 0, 255), 2)
cv2.imshow('Elon Musk', imgElon)
cv2.waitKey(0)
And the funny thing is that I am not getting this problem every time. It runs perfectly sometimes.
I installed opencv-python-4.2.0.32 and the problem seems to have went away. I was using version 4.3.0.36 when having the issues.
This will help. You need to resize the image sometime the OpenCV messes with an image format this will work in all OpenCV versions hope this helps
import cv2
import numpy as np
import face_recognition
# cv2.namedWindow('image', cv2.WINDOW_NORMAL)
imgElon = face_recognition.load_image_file("elon.jpg")
print(type(imgElon.shape))
a,b,c=imgElon.shape
imgElon = cv2.cvtColor(imgElon, cv2.COLOR_BGR2RGB)
imgElon_face_loc = face_recognition.face_locations(imgElon)[0]
print(imgElon_face_loc)
imgElon_encode = face_recognition.face_encodings(imgElon)[0]
cv2.rectangle(imgElon, (imgElon_face_loc[0], imgElon_face_loc[3]), (imgElon_face_loc[1], imgElon_face_loc[2]),(255, 0, 255), 2)
imgElon=cv2.resize(imgElon, (a, b))
cv2.imshow('image', imgElon)
cv2.waitKey(0)
cv2.destroyAllWindows()
I had the same problem, and was able to solve it using this code:
image = cv2.imread("./faces/test.jpg", cv2.IMREAD_COLOR)

Argument error when compiling .exe from Python using PyInstaller

I am trying to write a screen recorder program in python. My code runs normally in the compiler. But when I convert it to .exe, it raises this error:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): project.avi in function 'cv::icvExtractPattern'
I used pyinstaller to convert to .exe.
This is my code:
from tkinter import*
from tkinter import messagebox as msj
from PIL import ImageTk, Image
from PIL import ImageGrab
import os
import time
import cv2
import numpy as np
import glob
recording=False
i = 0
size = 100, 100
mainWindow=Tk()
mainWindow.title("ScreenRecorder")
mainWindow.geometry("200x200")
scriptDirectory = (os.path.dirname(os.path.realpath(__file__)))
def convert(imageCount):
img_array = []
for ip in range(1,imageCount):
x="snap"+str(ip)+".jpg"
for filename in glob.glob(x):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 9, size)
for iz in range(len(img_array)):
out.write(img_array[iz])
out.release()
for a in range(1,imageCount+1):
os.remove("snap"+str(a)+".jpg")
def record():
global i
print(recording)
if(recording==True):
i+=1
fileName= ("snap"+str(i))
#time.sleep(0.00005)
image = ImageGrab.grab()
name=fileName+".jpg"
image.save(name,'JPEG')
imgX = (Image.open("snap"+str(i)+".jpg"))
imgX= imgX.resize(size, Image.ANTIALIAS)
imgX=ImageTk.PhotoImage(imgX)
mainWindow.after(1, record)
def startButton():
global recording
print("ehe")
recording=True
record()
def stopButton():
global recording
recording=False
record()
convert(i)
startButton=Button(text="Start",command=startButton)
startButton.pack()
stopButton=Button(text="Stop",command=stopButton)
stopButton.pack()
mainWindow.after(1, record)
mainWindow.mainloop()
I can just advise you to use another method, i think it's more simple, try to use 'auto py to exe'.This is a module that can be installed from the net or from the pip installer.
see from here.This the only way that i use for my codes.
Secondly, iknow that if the program is not opened using the format of .py will never be opened at .exe
hope i helped you.

Live Screen Monitoring With Python3 Pytesseract

I am working on a python3 project on windows 10, and I was wondering if anyone knew of anyway to pass an opencv screen grab through pytesseract? If not, is there any other OCR that you could?
Here is the code for the opencv screen grab:
import numpy as np
from PIL import ImageGrab
import cv2
while True:
screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
cv2.imshow('window', cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
I know very little about pytesseract, but this might get you started:
#!/usr/bin/env python3
import numpy as np
from PIL import ImageGrab
import pytesseract
from PIL import Image, ImageEnhance, ImageFilter
from textblob import TextBlob
# Grab some screen
screen = ImageGrab.grab(bbox=(0,0,800,640))
# Make greyscale
w = screen.convert('L')
# Save so we can see what we grabbed
w.save('grabbed.png')
text = pytesseract.image_to_string(w)
correctedText = TextBlob(text).correct()
print(correctedText)
From this grab:
I got:
# Terminal Shell Edit View Window Help
The writing is on the wall

opencv2 python3 imread with NoneType

I program in Ubuntu system with python3, opencv2. There are several images in the folder that need to be processed. When I use imread, print(img.shape) shows AttributeError: 'NoneType' object has no attribute 'shape'. And I checked the created images' size is 0 bytes. The strange thing is that there are some images can be read successfully, but some are NoneType. Thanks for your help.
import glob as gb
import cv2
import random
import os
import numpy as np
shared_path="/home/train_1/"
folder_list=["HTC-1-M7"]
for j in range(len(folder_list)):
output_path=os.path.join("/home/test/",folder_list[j])
camera_path= os.path.join(shared_path,folder_list[j])
img_path = gb.glob(camera_path+"/*.jpg")
counter=1
for path in img_path:
img = cv2.imread(path)
print(img.shape)
kernel = np.array([[-1,2,-2,2,-1],[2,-6,8,-6,2],[-2,8,-12,8,-2],[2,-6,8,-6,2],[-1,2,-2,2,-1]],np.float32)/12
img = cv2.filter2D(img,-1,kernel)
It means that somewhere a function which should return a image just returned None and therefore it has no shape attribute.
Try print(img) to check if your image is None or an actual numpy object. You probably get this error because your image path may be wrong in a way. Make sure your path is completely correct.

Resources