Importing a tuple to a list from a function - python

I'm trying to modify pixels using range in a loop but I can't import the range from size function.
load = bnw.load()
loadpx = [
(a),
(b)
]
bnw.size(loadpx)
print(loadpx)
for x in a:
for y in b:
new = load[x,y] + 10
if new > 254:
new = 254
bnw = new
The output from bnw.size should be the number of pixels the image has ex. (1920,1080). after knowing the size a is inputted to the x and b to y.
the full code withe the first answer returned the same error
import tkinter as tk
import random
import os
import time
from tkinter import filedialog
from PIL import Image
import numpy as np
main_window = tk.Tk()
main_window.title("foto epic")
judul = tk.Label(main_window, text=" Editor Instagram epic 2 BnW Edition wkwk \n\n Silahkan Input foto Dibawah\n\/\n")
judul.pack()
def UploadAction():
file = filedialog.askopenfilename()
print('Selected:', file)
img = Image.open(file)
bnw2 = img.convert(mode = "L")
print(bnw2.size)
load = bnw2.load()
r,c = bnw2.size()
for x in range(r):
for y in range(c):
new = load[x,y] + 10
if new > 254:
new = 254
new = bnw2
arraying = np.asarray(bnw2)
counting = np.bincount(arraying.flatten(), minlength = 128)
px_num = np.sum(counting)
counting = counting/px_num
sum1 = np.cumsum(counting)
floorcount = np.floor(255 * sum1).astype(np.uint8)
donecount = list(arraying.flatten())
transforming = [floorcount[p] for p in donecount]
transforming = np.reshape(np.asarray(transforming), arraying.shape)
done_transform = Image.fromarray(transforming)
done = tk.Label(main_window, text=" \nFoto Telah di export!\nTerimakasih Sudah Menggunakan Program ini!\n")
done.pack()
done_transform.show()
if os.path.exists('result.jpg'):
done_transform.save('result_{}.jpg'.format(int(time.time())))
else:
done_transform.save('result.jpg')
button = tk.Button(main_window, text='Beautify!', command=UploadAction)
button.pack()
tk.mainloop()
I use Tkinter for UI I don't know if it would affect the original question
the error
Selected: D:/Code/Kuliah/Semester 3/citra/yes/DSC_3044.jpg
(4608, 1975) < the resolution if printed
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "d:\Code\Kuliah\Semester 3\citra\yes\Tugas Pengolahan Citra.py", line 22, in UploadAction
r,c = bnw2.size()
TypeError: 'tuple' object is not callable

Here i edited the answer this should work now:
file = filedialog.askopenfilename()
print('Selected:', file)
img = Image.open(file)
bnw2 = img.convert(mode = "L")
load = bnw2.load()
r,c = bnw2.size
for x in range(r):
for y in range(c):
new = load[x,y] + 10
if new > 254:
new = 254
load[x,y] = new

Related

Getting each list in matplotlib to be its own row within an eventplot

So basically here is the problem I've set out to solve. I have data that I want to graphically show for a paper. Basically, the data is organized into trials. Each trial has a tone and then positive vocalizations are measured. I've normalized the graph to the onset of the tone and the tone is 10 seconds long. The graph I have as far as the x axis is concerned is accurate. My problem lies in the y axis. I've basically created one main list as the data and then created a for loop to add each trial group of vocalizations in as its own list. Now my problem is that I want each trial to have a corresponding value on the y axis. There are sixty trials so ideally there should be a value of sixty on the y axis, and I should end up with each y value corresponding to a trial set. For some reason my graph isn't quite working like that. Here is my code
#%%imports and setup for initial data
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import pandas as pds
from tqdm import tqdm as tq
from pathlib import Path
import seaborn as sns
#%%Create Button Function for data input
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("Excel Files", "*.xlsx"),))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
width = window.winfo_screenwidth()
height = window.winfo_screenheight()
def close():
window.destroy()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
b2 = Button(window, text = "OK", command = close).pack()
window.geometry("%dx%d" % (width, height))
window.mainloop()
print(file_path)
#%%Read Excel File
ds = pds.read_excel(io = file_path, usecols = "A,D", skiprows = 1, keep_default_na = False)
#%%usv incident beggining times in seconds
usvTimes = ds["Begin Time (s)"].tolist()
#beginning times for tones in seconds
toneStart = ds["Tone Time Markers"].tolist()
toneStart2 = ds["Tone Time Markers"].tolist()
#%%creates empty lists to be used by loops later
graphStart = []
graphEnd = []
#%%creates the first parameter of the x value for each graph
print("Calculating GraphStart")
for num in tq(toneStart):
try:
int(float(num))
except:
pass
else:
graphStart.append(num - 10)
print("Complete")
#%%creates the second parameter of the x value for each graph
print("Calculating GraphEnd")
for num in tq(toneStart2):
try:
int(float(num))
except:
pass
else:
graphEnd.append(num + 10)
print("Complete")
#%%Makes usvTimes usable
print("Calculating USVTimeStamps")
for num in tq(usvTimes):
try:
int(float(num))
except:
pass
print("Complete")
#%%pair beggining and end parameter into a full list
graphpair = zip(graphStart,graphEnd)
#%%Zip x and y coordinates together
graphx = list(graphpair)
#%%create graphs
print("Input File Name:")
filename = str(input())
print("Creating Graphs")
myPath = str(Path.home() / "Downloads")
print(myPath)
lists = []
for index, num in tq(enumerate(graphx)):
x,y = num
leftbound = (x - x) - 30
rightbound = y - x
za = x - 10
zb = x + 10
sublist = []
for i in usvTimes:
try:
x + 0
except:
pass
if i == 0:
continue
elif za <= i <= zb:
sublist.append(i-x)
else:
continue
lists.append(sublist)
print(lists)
data = lists
plt.eventplot(data , colors='black' , lineoffsets=1 , linelengths=1)
plt.ylabel("Trial Number")
plt.xlabel("Time of USV Incidence Normalized to tone")
plt.savefig(myPath + "/Eventplot" + filename + str(num) + ".pdf")
plt.show()
print("Graphs Complete")

Plotted Images in Matplotlib Continue to get smaller, Final pdf doesn't show all plots

I'm trying to get multiple plots into a single figure. Having them in one column has been the approach I have been using but it isn't necessary. The problem I've been running into is that my figures will graph and each figure will be slightly smaller than the previous one. Additionally, the pdf I save from the figure is oddly proportioned and doesn't show all of the subplots. My commenting is slightly funky because I've been testing and cobbling from some of my old projects as well as the internet so don't look into it too much.
Here is my full code:
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import pandas as pds
from tqdm import tqdm as tq
from pathlib import Path
#%%Create Button Function for data input
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("Excel Files", "*.xlsx"),))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
width = window.winfo_screenwidth()
height = window.winfo_screenheight()
def close():
window.destroy()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
b2 = Button(window, text = "OK", command = close).pack()
window.geometry("%dx%d" % (width, height))
window.mainloop()
print(file_path)
#%%Read Excel File
ds = pds.read_excel(io = file_path, usecols = "A,D", skiprows = 1, keep_default_na = False)
#%%usv incident beggining times in seconds
usvTimes = ds["Begin Time (s)"].tolist()
#beginning times for tones in seconds
toneStart = ds["Tone Time Markers"].tolist()
toneStart2 = ds["Tone Time Markers"].tolist()
#%%creates empty lists to be used by loops later
graphStart = []
graphEnd = []
#%%creates the first parameter of the x value for each graph
print("Calculating GraphStart")
for num in tq(toneStart):
try:
int(float(num))
except:
pass
else:
graphStart.append(num - 30)
print("Complete")
#%%creates the second parameter of the x value for each graph
print("Calculating GraphEnd")
for num in tq(toneStart2):
try:
int(float(num))
except:
pass
else:
graphEnd.append(num + 30)
print("Complete")
#%%Makes usvTimes usable
print("Calculating USVTimeStamps")
for num in tq(usvTimes):
try:
int(float(num))
except:
pass
print("Complete")
#%%pair beggining and end parameter into a full list
graphpair = zip(graphStart,graphEnd)
#%%Zip x and y coordinates together
graphx = list(graphpair)
#%%create graphs
print("Creating Graphs")
myPath = str(Path.home() / "Downloads")
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
for index, num in tq(enumerate(graphx)):
x,y = num
leftbound = x
rightbound = y
graphnum = index + 1
a = []
for x in usvTimes:
try:
x + 0
except:
pass
else:
if leftbound <= x <= rightbound:
a.append(x)
plt.figure()
plt.subplot(graphnum,1,graphnum)
plt.hlines(1, leftbound, rightbound)
plt.eventplot(a, orientation='horizontal', colors='b')
plt.xlabel("Time in Recording (s)")
plt.ylabel("Arbitrary Axis (Abu)")
else:
pass
plt.savefig(myPath + "/Eventplot" + ".pdf")
print("Graphs Complete")

Python Tkinter return self.func(*args) and TypeError:list indices must be integers or slices, not str

The goal is to extract excel data and write it to a text file, based on an input through tkinter. The Tkinter box is popping up, but when the entry input is given, it produces an error in the terminal.
I have tried changing the line 30 int or float.
Thank you for any help you can give.
The code below is creating this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\bob\AppData\Local\Programs\Python\Python37-
32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "c:/Users/bob/Dropbox/Financial/PERSONAL FINANCES/budget.py",
line 30, in click
result = np.array(sheet.cell_value(i,budget_col))
File "C:\Users\bob\AppData\Local\Programs\Python\Python37-
32\lib\site-packages\xlrd\sheet.py", line 419, in cell_value
return self._cell_values[rowx][colx]
TypeError: list indices must be integers or slices, not str
My code:
import os
from tkinter import *
import time
import xlrd
import numpy as np
os.system('cls' if os.name == 'nt' else 'clear')
def click():
file_location = 'C:/Users/bob/Dropbox/Financial/PERSONAL FINANCES/NEW DOUBLE ENTRY PERSONAL.xlsx'
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(6)
budget_col = textentry.get()
excel_col1 = np.array([])
array_length = sheet.nrows
for i in range(array_length):
result = np.array(sheet.cell_value(i,0))
excel_col1 = np.append(excel_col1,[result])
excel_col2 = np.array([])
for i in range(array_length): # 0 to total rows
result = np.array(sheet.cell_value(i,1))
excel_col2 = np.append(excel_col2,[result])
excel_col_bud_col = np.array([])
for i in range(array_length): # 0 to total rows
result = np.array(sheet.cell_value(i,budget_col))
excel_col_bud_col = np.append(excel_col_bud_col,[result])
#Writing text file to desktop
# CREATING THE textfile:
created_name = '\curr_budget.txt'
if os.name == 'nt':
desktop = str(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'))
query_if_windows = "windows"
else:
desktop = str(os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop'))
query_if_windows = "not windows"
filename = desktop + created_name
text_file = open(filename,"w")
text_file.write(time.strftime("%c\n"))
text_file.write("\n")
text_file.write('Accounts - Budget\n')
text_file.write("\n")
for n in range(4,sheet.nrows-2):
x = excel_col_bud_col[n]
y = excel_col2[n]
z = excel_col1[n]
text_file.write(z + " " + x + " " + y)#,"{bud:8.8} {name}".format(name=y,bud=x))
text_file.write("\n")
text_file.write("\n")
text_file.write('Note, some debit card transactions will take a few days so will not appear above\n')
text_file.close()
window = Tk()
window.title("Print Budget to Desktop")
window.configure(background="white")
Label (window,text="Enter column across, starting at 0, where this month's budget is located", bg="white", fg = "black", font="none 12 bold") .grid(row=0, column=0, sticky=W)
textentry = Entry(window, width=20,bg="white") #column '15' for August budget (starts at 0)
textentry.grid(row=1,column=0,sticky=W)
Button(window, text="Print Budget to Desktop",width=23,command=click) .grid(row=2,column=0,sticky=W)
window.mainloop()
The error telling you precisely what the problem is. It is saying you need to pass an integer rather than a string to a particular function. That is happening because of these two lines:
budget_col = textentry.get()
...
result = np.array(sheet.cell_value(i,budget_col))
budget_col is a string, but sheet.cell_value requires an integer. You need to convert the value you get from textentry.get() to an integer before you can pass it to that function.

Image To Text File Code (Python) Not Running Correctly

When I try to run the script (I'm on a Mac; I press command B, right?), instead of generating the txt file, nothing happens. (The only Traceback info is something that, I think, always comes up and usually the code will run anyway--
Traceback (most recent call last):
File "/Users/[my name]/Downloads/ImportImageTextFile.py", line 2, in <module>
import rhinoscriptsyntax as rs
ImportError: No module named rhinoscriptsyntax
Here's the code so far (sorry that some of this is not relevant--the code I am pasting 1. turns a jpg into a text file and 2. puts the text file into rhino).
# Import points from a text file
import rhinoscriptsyntax as rs
from System.Drawing import Color
recreateImage = False
def main():
# import the converted pixel image and store the RGB values in "pixels":
# note: the resultant list will be organized as follows:
# the first 2 [] indicates the y and x coordinates
# the last [] indicates the color (red = 0 , green = 1 , blue = 2)
# pixels[y][x] = [R,G,B] to get the blue value at pixel 11 in the first row: pixels[11][0][2]
# you can get the width of the pixel image by using: w = len(pixels[0]) (this returns the length of the list of the first row or X-dimension)
# you can get the height of the pixel image by using: h = len(pixels) (this returns the length/number of "columns" or Y-dimension)
pixels = importPoints(recreateImage)
# the 4 is the "step value"
for x in range (0, len(pixels[0]) , 2):
for y in range (0, len(pixels) , 2):
r = pixels[y][x][0]
g = pixels[y][x][1]
b = pixels[y][x][2]
# we save the "AddSphere" into the phrase spId
# we subtract the y to not let the image mirror/ make the pixelated image higher than the original image, otherwise it would be directly above the original image
# the "3 - (r+g+b)/765" represents the sphere radius size
# spId = rs.AddSphere([x,len(pixels)-y,(r+g+b)/765*30], 3 - (r+g+b)/765 )
# rs.ObjectColor(spId, [r,g,b])
# lines have a start point and an end point
# [] / brackets indicate a new array/list
lineId = rs.AddLine ( [x, -y , r+g+b] , [x, -y , 0] )
rs.ObjectColor (lineId, [r,g,b])
def importPoints(makeImage):
#prompt the user for a file to import
filter = "Text file (*.txt)|*.txt|All Files (*.*)|*.*||"
filename = rs.OpenFileName("Open Pixel File", filter)
if not filename: return
#read each line from the file
file = open(filename, "r")
contents = file.readlines()
if (makeImage):
previousLayer = rs.CurrentLayer()
rs.AddLayer("Image")
rs.CurrentLayer("Image")
counterX = -1
counterY = -1
width = 0
height = 0
imagePixels = []
pixelRow = []
#browse through each line in the text file:
for text in contents:
items = text.strip("()\r\n").split(";")
#print (str(items))
if (counterX == -1 and counterY == -1):
counterY +=1
width = int(items[1].split(",")[1])
height = int(items[2].split(",")[1])
print ("Image size: "+str(width)+" x "+str(height))
else:
r = int(items[0])
g = int(items[1])
b = int(items[2])
counterX +=1
if (counterX == width):
counterY +=1
counterX = 0
imagePixels.append(pixelRow)
pixelRow = []
if (makeImage):
ptId = rs.AddPoint ([counterX, -counterY, 0])
rs.ObjectName (ptId, str(counterX)+" - "+str(counterY)+" : "+str(r)+","+str(g)+","+str(b))
rs.ObjectColor (ptId, [r,g,b])
pixelRow.append([r,g,b])
file.close()
if (makeImage):
rs.CurrentLayer(previousLayer)
return imagePixels
main()
Thank you so much!

downsampling images as a function in Python

I am trying to resample some tiff files from 2000*2000 to 500*500.
I have created a function and I tried for one file and it worked nicely. Now I want to apply it for all the available file I have.
I want to write the output of the function and I have written the code based on my knowledge and I receive error on the writing out_file. I have copied the both function and main code for your consideration. The main code just read the tif files according to their naming and applies the function. I would be thankful if sb could guide me where my mistake is.
#*********function********************
def ResampleImage(infile):
fp = open(infile, "rb")
p = ImageFile.Parser()
while 1:
s = fp.read()
if not s:
break
p.feed(s)
img = p.close()
basewidth = 500
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
outfile=img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
return outfile
#********* main code********
import os,sys
import ImageResizeF
import PIL
from PIL import Image
from PIL import Image,ImageFile
tpath = 'e:/.../resampling_test/all_tiles/'
tifext = '.tif'
east_start = 32511616
north_start = 5400756
ilist = range (0,14)
jlist = range (0,11)
north = north_start
ee = ',4_'
en = ',2'
for i in ilist:
east = east_start
north = north_start + i * 400
snorth = str (north)
for j in jlist:
east = east_start + j * 400
seast = str (east)
infile = tpath + seast + ee + snorth + en + tifext
output = tpath + seast + ee + snorth + en + '_res'+tifext
out_file = ImageResizeF.ResampleImage(infile)
out_file.write (output)
out_file.close ()
Your error is probably related to what you are returning from ImageResizeF.ResampleImage, is it a file handle? Otherwise you are doing it wrong because you cannot close() something which is not a file handle. You should do the whole file processing inside the function or return an image object, for example:
def process_image(image):
"Processes the image"
image.resize((x, y), Image.ANTIALIAS) # or whatever you are doing to the image
return image
image = Image.open('infile.tiff')
proc_image = process_image(image)
proc_image.save('outfile.tiff')

Categories