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!
Related
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")
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
Hey I am having this Index Error where I am trying to composite events but my indices start at 0 and not 1 and while have tried to do a number of things like trying to .append[i+1] I am unable to fix this error I am having.
Theres apparently something wrong with this specific line of code : dset_IDX[offset:offset_next] = event_id[file_indices]
While the .py file is over a 1000 lines of code so I can not show all of it I am able to show the part of the function that is giving me the error
def count_events(files):
# Because we want to remove events with 0 hits,
# we need to count the events beforehand (to create the h5 file).
# This function counts and indexes the events with more than 0 hits.
# Files need to be iterated in the same order to use the indexes.
""" This is where we manually specify the file"""
num_events = 0
nonzero_file_events = []
for file_index, f in enumerate(files):
data = np.load(f, allow_pickle=True)
nonzero_file_events.append([])
hits = data['digi_hit_pmt']
for i in range(len(hits)):
if len(hits[i]) != 0:
nonzero_file_events[file_index].append(i)
num_events += 1
return num_events, nonzero_file_events
def GenMapping(csv_file):
mPMT_to_index = {}
with open(csv_file) as f:
rows = f.readline().split(",")[1:]
rows = [int(r.strip()) for r in rows]
for line in f:
line_split = line.split(",")
col = int(line_split[0].strip())
for row, value in zip(rows, line_split[1:]):
value = value.strip()
if value: # If the value is not empty
mPMT_to_index[int(value)] = [col, row]
npmap = np.zeros((max(mPMT_to_index) + 1, 2), dtype=np.int)
for k, v in mPMT_to_index.items():
npmap[k] = v
return npmap
def GenerateMultiMuonSample_h5(avg_mu_per_ev=2.5, sigma_time_offset=21.2):
"""
Inputs:
avg_mu_per_ev == Poisson distribution mean for number of muons in each spill
sigma_time_offset == Width of spill (Gaussian) in nanoseconds
"""
files = ['event998.npz']
# Remove whitespace
files = [x.strip() for x in files]
# Check that files were provided
if len(files) == 0:
raise ValueError("No files provided!!")
print("Merging " + str(len(files)) + " files")
# Start merging
num_nonzero_events, nonzero_event_indexes = count_events(files)
print(num_nonzero_events)
# np.random.poisson( avg_mu_per_ev, number_of_throws )
num_muons = np.random.poisson(avg_mu_per_ev, num_nonzero_events - 2954)
# creates h5 file to generate the h5 file
dtype_events = np.dtype(np.float32)
dtype_labels = np.dtype(np.int32)
dtype_energies = np.dtype(np.float32)
dtype_positions = np.dtype(np.float32)
dtype_IDX = np.dtype(np.int32)
dtype_PATHS = h5py.special_dtype(vlen=str)
dtype_angles = np.dtype(np.float32)
# sets h5 file to be written
h5_file = h5py.File('multimuonfile(2).h5', 'w')
dset_event_data = h5_file.create_dataset("event_data",
shape=(num_nonzero_events,) + IMAGE_SHAPE,
dtype=dtype_events)
dset_labels = h5_file.create_dataset("labels",
shape=(num_nonzero_events,),
dtype=dtype_labels)
dset_energies = h5_file.create_dataset("energies",
shape=(num_nonzero_events, 1),
dtype=dtype_energies)
dset_positions = h5_file.create_dataset("positions",
shape=(num_nonzero_events, 1, 3),
dtype=dtype_positions)
dset_IDX = h5_file.create_dataset("event_ids",
shape=(num_nonzero_events,),
dtype=dtype_IDX)
dset_PATHS = h5_file.create_dataset("root_files",
shape=(num_nonzero_events,),
dtype=dtype_PATHS)
dset_angles = h5_file.create_dataset("angles",
shape=(num_nonzero_events, 2),
dtype=dtype_angles)
# 22 -> gamma, 11 -> electron, 13 -> muon
# corresponds to labelling used in CNN with only barrel
# IWCDmPMT_4pi_full_tank_gamma_E0to1000MeV_unif-pos-R371-y521cm_4pi-dir_3000evts_329.npz has an event
# with pid 11 though....
# pid_to_label = {22:0, 11:1, 13:2}
offset = 0
offset_next = 0
mPMT_to_index = GenMapping(PMT_LABELS)
# Loop over files
for file_index, filename in enumerate(files):
data = np.load(filename, allow_pickle=True)
nonzero_events_in_file = len(nonzero_event_indexes[file_index])
x_data = np.zeros((nonzero_events_in_file,) + IMAGE_SHAPE,
dtype=dtype_events)
digi_hit_pmt = data['digi_hit_pmt']
# digi_hit_charge = data['digi_hit_charge']
# digi_hit_time = data['digi_hit_time']
# digi_hit_trigger = data['digi_hit_trigger']
# trigger_time = data['trigger_time']
delay = 0
# Loop over events in file
# Loop over number of muons in each event
event_id = np.array([], dtype=np.int32)
root_file = np.array([], dtype=np.str)
pid = np.array([])
position = np.array([])
direction = np.array([])
energy = np.array([])
labels = np.array([])
# with open("ResultFile.txt", "w") as text_file:
# sys.stdout = open("Result2.txt", "w")
for i, nmu in enumerate(num_muons):
# np.savetxt(text_file, i, nmu,fmt="%d")
# text_file.write("processing output entry " + str(i) + " with " + nmu + " muons")
print("processing output entry ", i, " with ", nmu, " muons")
indices = np.random.randint(0, len(digi_hit_pmt), max(1, nmu))
time_offs = [0.]
if nmu > 1:
time_offs = np.append(time_offs, np.random.normal(0., sigma_time_offset, nmu - 1))
hit_pmts, charge, time = SumEvents(indices, time_offs, data, nmu == 0)
hit_mpmts = hit_pmts // 19
pmt_channels = hit_pmts % 19
rows = mPMT_to_index[hit_mpmts, 0]
cols = mPMT_to_index[hit_mpmts, 1]
x_data[i - delay, rows, cols, pmt_channels] = charge
x_data[i - delay, rows, cols, pmt_channels + 19] = time
# fix below!!!
idx0 = indices[0]
event_id = np.append(event_id, data['event_id'][idx0])
root_file = np.append(root_file, data['root_file'][idx0])
pid = np.append(pid, data['pid'][idx0])
position = np.append(position, data['position'][idx0])
direction = np.append(direction, data['direction'][idx0])
energy = np.append(energy, np.sum(data['energy'][indices]))
labels = np.append(labels, nmu)
offset_next += nonzero_events_in_file
file_indices = nonzero_event_indexes[file_index]
dset_IDX[offset:offset_next] = event_id[file_indices]
dset_PATHS[offset:offset_next] = root_file[file_indices]
dset_energies[offset:offset_next, :] = energy[file_indices].reshape(-1, 1)
dset_positions[offset:offset_next, :, :] = position[file_indices].reshape(-1, 1, 3)
dset_labels[offset:offset_next] = labels[file_indices]
print(event_id)
direction = direction[file_indices]
polar = np.arccos(direction[:, 1])
azimuth = np.arctan2(direction[:, 2], direction[:, 0])
dset_angles[offset:offset_next, :] = np.hstack((polar.reshape(-1, 1), azimuth.reshape(-1, 1)))
dset_event_data[offset:offset_next, :] = x_data
offset = offset_next
print("Finished file: {}".format(filename))
#sys.stdout.close()
print("Saving")
#h5_file.close()
print("Finished")
# In[ ]:
GenerateMultiMuonSample_h5(avg_mu_per_ev=2.5, sigma_time_offset=21.2)
Traceback
Merging 1 files
2958
processing output entry 0 with 3 muons
processing output entry 1 with 1 muons
processing output entry 2 with 3 muons
processing output entry 3 with 3 muons
Traceback (most recent call last):
File "C:/Users/abdul/OneDrive/Desktop/ISSP/ISSP-AA/TriumfCNN-AA/EventDisplay.py", line 1068, in <module>
GenerateMultiMuonSample_h5(avg_mu_per_ev=2.5, sigma_time_offset=21.2)
File "C:/Users/abdul/OneDrive/Desktop/ISSP/ISSP-AA/TriumfCNN-AA/EventDisplay.py", line 1044, in GenerateMultiMuonSample_h5
dset_IDX[offset:offset_next] = event_id[file_indices]
IndexError: index 4 is out of bounds for axis 0 with size 4
not much info is provided but what i have understood,
the error says that axis 0 has size=4 and you are trying to access index 4 which is not possible with size 4 as it starts with 0 and max index could be 3.
I am trying to compare one image with all images of another file , get the difference percentage and print file name of the least difference percentage .... if i try to append the output differences to a list ... i get an error saying " float values cannot be iterated".... this is what i have done so far ....
from itertools import izip
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
from PIL import Image
import math
res = 0
def take_and_save_picture(im_save):
'''Take a picture and save it
Args:
im_save: filepath where the image should be stored
'''
camera_port = 0
ramp_frames = 30
cap = cv2.VideoCapture(camera_port)
def get_image():
retval, im = cap.read()
return im
for i in xrange(ramp_frames):
temp = get_image()
print("Taking image...")
# Take the actual image we want to keep
camera_capture = get_image()
#im_save_tmp = im_save + '.jpg'
im_save_tmp = im_save
# A nice feature of the imwrite method is that it will automatically choose the
# correct format based on the file extension you provide. Convenient!
cv2.imwrite(im_save_tmp, camera_capture)
# You'll want to release the camera, otherwise you won't be able to create a new
# capture object until your script exits
# del(cap)
img1 = cv2.imread(im_save_tmp, 0)
edges = cv2.Canny(img1, 100, 200)
cv2.imwrite(im_save, edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
def re(path1,path2):
#path1 = raw_input("Enter the path1:")
#path2 = raw_input("Enter the path2:")
i2= Image.open(path2)
listing = os.listdir(path1)
for file in listing:
i1 = Image.open(path1 + file)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
res = (dif / 255.0 * 100) / ncomponents
print "Difference (percentage):", res
def main():
capture_img = "/Users/Me/Documents/python programs/New/pro.png"
#img_to_compare = "/Users/Me/Documents/python programs/compare/img2.jpg"
take_and_save_picture(capture_img)
path1 = "/Users/Me/Documents/python programs/New/numbers1/"
path2 = "/Users/Me/Documents/python programs/New/pro.png"
re(path1,path2)
if __name__ == '__main__':
main()
the output is the difference
Difference (percentage): 2.52484809028
Difference (percentage): 2.64822048611
Difference (percentage): 2.64822048611
Difference (percentage): 3.55436197917
the values that i get in "res" have to be stored in a list and the minimum value should be found and printed.... please give me some code ... totally new to python ... thank you ...
You're code must be like this:
#######
list_dif = []
def re(path1,path2):
#path1 = raw_input("Enter the path1:")
#path2 = raw_input("Enter the path2:")
i2= Image.open(path2)
listing = os.listdir(path1)
for file in listing:
i1 = Image.open(path1 + file)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
#######
for n in range(ncomponents):
res = (dif / 255.0 * 100) / (ncomponents + 1)
list_dif.append(res)
print "Difference (percentage):", list_dif
Something like this?
def re(path1,path2):
#path1 = raw_input("Enter the path1:")
#path2 = raw_input("Enter the path2:")
i2= Image.open(path2)
listing = os.listdir(path1)
res = []
for file in listing:
i1 = Image.open(path1 + file)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
res.append((dif / 255.0 * 100) / ncomponents)
print "Difference (percentage):", res
minimum = min(res) # Find minimum value in res
print(minimum)
How do I save an image file from data manipulated using image.load()?
This is my code used to merge two pictures of the same size
from PIL import Image
import random
image1 = Image.open("me.jpg")
image2 = Image.open("otherme.jpg")
im1 = image1.load()
im2 = image2.load()
width, height = image1.size
newimage = Image.new("RGB",image1.size)
newim = newimage.load()
xx = 0
yy = 0
while xx < width:
while yy < height:
if random.randint(0,1) == 1:
newim[xx,yy] = im1[xx,yy]
else:
newim[xx,yy] = im2[xx,yy]
yy = yy+1
xx = xx+1
newimage.putdata(newim)
newimage.save("new.jpg")
When I run it I get this error though.
Traceback (most recent call last):
File "/home/dave/Desktop/face/squares.py", line 27, in <module>
newimage.putdata(newim)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1215, in putdata
self.im.putdata(data, scale, offset)
TypeError: argument must be a sequence
Isn't the dictionary from using .load() a sequence? I can't find anyone else on google having this problem.
The dictionary (which isn't really a dictionary) returned by load is the data in the image. You don't have to reload it with putdata. Just remove that line.
Also, use a for loop instead of a while loop:
for xx in range(0, width):
for yy in range(0, height):
if random.randint(0,1) == 1:
newim[xx,yy] = im1[xx,yy]
else:
newim[xx,yy] = im2[xx,yy]
Now there's no need to initialize and increment xx and yy.
You could even use itertools.product:
for xx, yy in itertools.product(range(0, width), range(0, height)):
if random.randint(0,1) == 1:
newim[xx,yy] = im1[xx,yy]
else:
newim[xx,yy] = im2[xx,yy]