I am new in programming, and I would like to make a picture resizer with gui.
I have problems with making the gui.
I grabbed the problematic part of the code:
from tkinter import *
from tkinter import filedialog
import os, backend, glob2, cv2
loaded_pics=[]
picture_read=[]
window = Tk()
browsed_dir = StringVar()
browsed_dir.set(filedialog.askdirectory(initialdir="/",title='Please select a directory'))
file_path = browsed_dir.get()#+"/"
for filename in os.listdir(file_path):
if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')):
loaded_pics.append(filename)
print(loaded_pics)
try:
for images in loaded_pics:
imgs = cv2.imread(images, 1)
print(imgs)
except:
print("ERROR")
window.destroy()
window.mainloop()
So, I have got a list of .png/.jpg/.bmp files, I can print the list, but I cannot read them with cv2.imread(), when I print(imgs), I got "None"-s.
(I have not managed to make this with glob2. It is work well with current directory, but I could not make it with filedialog.)
I hope someone can help.
Thanks in advance!
You are building a list of filenames in loaded_pics. But this doesn't include the name of the directory, file_path. So when you call imread, your image is actually located at file_path/filename, but you are only passing filename. So cv2 cannot find your file, and returns None.
Related
I am currently trying to make a program for file organisation. I want my script to open a filedialog that asks for a sourcefolder where the files will be organised in based on their extension. After a sourcefolder has been selected, I want my script to make directories in that sourcefolder. I am a bit stuck on that last part.
import os
import shutil
from os import listdir
from os.path import isfile, join
import tkinter as tk
from tkinter import filedialog
from tkinter import *
print('This is a program that organises files in a given directory')
print(''
'')
print('Please select the folder in which you want to organise your files')
''' Source Folder '''
root = Tk()
root.withdraw()
source_path = filedialog.askdirectory()
The part above works just fine.
''' Create destination folders in the source folder '''
newpath1 = r'source_path\Images'
if not os.path.exists(newpath1): # check to see if they already exist
os.makedirs(newpath1)
newpath2 = r'source_path\Documents'
if not os.path.exists(newpath2):
os.makedirs(newpath2)
newpath3 = r'source_path\Else'
if not os.path.exists(newpath3):
os.makedirs(newpath3)
This, however, does not. It just removes files, or places them somewhere I cannot find them.
Any help would be greatly appreciated.
TLDR: how to make directories in a sourcefolder submitted with filedialog.
I use tkinter make interface to select folder directory and i get C:/Users/dtung/Desktop/ and i want to convert it to C:\Users\dtung\Desktop\ because i use autoit to select file. this is my code
import_file_path = filedialog.askdirectory()
list = os.listdir(path=import_file_path)
import_file_path.replace("/","\\")
replace function does't work with any string or character(dont have any error it just does't work), when i print it out i just received old string.
I don't understand your problem. The code above works fine for me.
import os
from tkinter import filedialog
import_file_path = filedialog.askdirectory()
list = os.listdir(path=import_file_path)
print('Before', import_file_path)
import_file_path = import_file_path.replace("/", os.sep)
print(os.path.join(import_file_path))
print('After', import_file_path)
prints out this on my Windows machine
Before C:/Users/Mega/Documents/HuaweiMusic
C:\Users\Mega\Documents\HuaweiMusic
After C:\Users\Mega\Documents\HuaweiMusic
By the way, why do you need to mix Autoit and Python?
You can use this code to fix the problem:
import os
from tkinter import filedialog
import_file_path = filedialog.askdirectory()
list = os.listdir(path=import_file_path)
import_file_path = import_file_path.replace("/", "\\")
i want to select an image and save the path in a variable. Then I want to use this variable to display the image. For this I have used the following code:
def open_dialog_box(self):
filename, _ = np.asarray(QFileDialog.getOpenFileNames(self, 'Select Multi File', 'default', 'All Files (*)'))
for name in filename:
#import pic
pic = cv2.imread(name, cv2.IMREAD_ANYDEPTH) #This doesn't works
**pic = cv2.imread("C:\\Users\\Image_name", cv2.IMREAD_ANYDEPTH)** #This works
cv2.imshow("Window", pic)
app = QApplication(sys.argv)
w = Fenster()
w.show()
sys.exit(app.exec_())
The bold line works. But I don't want to enter the whole path every time. I want the path to be automatically stored in a variable and then used to display the image. Is there a method to use a variable instead of typing the whole path ?
I tried this to see if it is working for you:
import cv2
import os.path
xp2 = os.path.abspath("")
#xp2 is having the path of the image, currently it is having pwd.
#print(xp2)
xp3 = xp2+"\screenshot.png"
#xp3 is the new variable with ur file name as to be used
img_1 = cv2.imread(xp3)
print(img_1)
on printing the img_1 I get the o/p of image.
Now you can use this path as per your need in your program.
Newish Python guy here. I've written what I thought would be a fairly simple script to extract the creation date metadata from photos and video and move them to a new folder based on year and month. I'm using PIL for picture and hachoir for video metadata.
For the most part I've got it working until I actually use shutil.move. At that point all the jpg's move to the new folders just fine. But all the videos are being COPIED. The original files are being left in the source folder.
My assumption is that some process that I invoke during the script is still accessing the video file and not letting it be deleted. Can anyone tell me what I'm messing up, and how I can release these video files to be moved?
========================
import os.path, time, sys, shutil
from PIL import Image
from PIL.ExifTags import TAGS
from hachoir_core.error import HachoirError
from hachoir_core.cmd_line import unicodeFilename
from hachoir_parser import createParser
from hachoir_core.tools import makePrintable
from hachoir_metadata import extractMetadata
from hachoir_core.i18n import getTerminalCharset
def get_field (exif,field) :
for (k,v) in exif.iteritems():
if TAGS.get(k) == field:
return v
for picture in os.listdir(os.getcwd()):
if picture.endswith(".jpg") or picture.endswith(".JPG"):
print picture
rawMetadata = Image.open(picture)._getexif()
datetime = get_field(rawMetadata, 'DateTime')
datedict = {'year' : datetime[0:4], 'month' : datetime[5:7]}
target = datedict['year']+'-'+ datedict['month']
if not os.path.isdir(target):
newdir = os.mkdir(target)
if picture not in target:
shutil.move(picture, target)
if picture.endswith('.mov') or picture.endswith('.MOV') or \
picture.endswith('mp4') or picture.endswith('.MP4'):
picture, realname = unicodeFilename(picture), picture
parser = createParser(picture, realname)
rawMetadata = extractMetadata(parser)
text = rawMetadata.exportPlaintext()
datedict = {'year' : text[4][17:21], 'month' : text[4][22:24]}
target = datedict['year']+'-'+ datedict['month']
dest = os.path.join(target, picture)
if not os.path.isdir(target):
newdir = os.mkdir(target)
if picture not in target:
try:
shutil.move(picture, dest)
except WindowsError:
pass
The in operator says whether items are in collections (e.g. an element in a list) or strings are substrings of other strings. It doesn't know that your string variable target is the name of a directory, nor does it know anything about checking directories to see if files are in them. Instead, use:
if os.path.exists(dest):
It's hard to tell what exactly is failing without a decent error code. Use this in your except block to get more answers:
except WindowsError as e:
print("There was an error copying {picture} to {target}".format(
picture=picture,target=target))
print("The error thrown was {e}".format
(e=e))
print("{picture} exists? {exist}".format(
picture=picture, exist=os.exists(picture))
print("{target} exists? {exist}".format(
target=target,exist=os.exists(target))
Note that much can be said for the logging module for errors like these. It's rather outside the scope of this question, though.
I'm starting to learn Python, and I thought to create a converter from a file to another (for example, from png to avi or between other file extensions) under Windows OS for now.
I wrote a script which works fine and it completes the conversion process, but I want improve it in functionality (and then in graphics); I'm using Tkinter and I thought to load the files with the possibility to drag-and-drop them as input for the next conversion command, instead of open a folder in which to put files as "input source". I found this topic (python drag and drop explorer files to tkinter entry widget) and I used it in this way:
import sys
import os
import Tkinter
from tkdnd_wrapper import TkDND
import shlex, subprocess
from subprocess import Popen, PIPE
import glob
import shutil
root = Tkinter.Tk()
dnd = TkDND(root)
entry = Tkinter.Entry()
entry.grid()
def handle(event):
inputfilespath = event.data
event.widget.insert(0, inputfilespath)
filesdir = os.path.dirname(os.path.realpath(inputfilespath))
files = glob.iglob(os.path.join(filesdir, "*.myext"))
for inputfilespath in files:
if os.path.isfile(inputfilespath):
subprocess1 = subprocess.Popen([...conversion command given as list, not string...], shell=True)
print "\n\nConversione in corso..."
subprocess1.wait()
subprocess1.terminate()
print "\n\nProcesso terminato!"
dnd.bindtarget(entry, handle, 'text/uri-list')
root.mainloop()
The problems:
If filename has a space, there is no conversion, and process ends without even notify any error too. "inputfilespath" wants to be the generic name for all the input files which I selected, and (for what I read) I can't (?) use quotes for an environment variable hoping to include filename's whitespace...
I tried to copy different files (with the same file extension and without whitespaces into the filename) in the same folder, and if I drag-and-drop only one of them on the Entry widget, the process starts fine (and this is great!), but it continues also for all the other no-selected files with the same extension in the same folder, whereas if I drag-and-drop multiple files on the Entry widget, no conversion occurs....
It seems that filenames containing whitespace are being wrapped in braces
(Tcl list style). To get a usable filelist, you should be able to do
something like:
import Tkinter
from untested_tkdnd_wrapper import TkDND
def handle(event):
files = root.tk.splitlist(event.data)
for filename in files:
event.widget.insert('end', filename)
root = Tkinter.Tk()
lb = Tkinter.Listbox(root, width=50)
lb.pack(fill='both', expand=1)
dnd = TkDND(root)
dnd.bindtarget(lb, handle, 'text/uri-list')
root.mainloop()
Just use the tkinter file dialog, then just have it insert the files into the entry box.
Example:
filedialog = tkFileDialog.askopenfilenames(*options*)
entry.insert(END, filedialog)
Example Using StringVar:
entryVar = StringVar()
entry = Entry(textvariable=entryVar)
filedialog = tkFileDialog.askopenfilenames(*options*)
entryVar.set(filedialog
Hope this helps!