pix[x,y] from PIL produces name error - python-2.7

I am a beginner programmer and I am trying to access pixel data from a picture using python. I want to eventually get the pixel data into an array. I searched the web for the code of how to do this and this is what I got:
from PIL import Image
im = Image.open("C:/Users/Owner/Desktop/bw.png")
pix = im.load()
print pix[x,y]
pix[x,y] = value
It seems to work fine until I get to the print[x,y] line. I get an error saying "NameError: name 'x' is not defined". I have downloaded PIL 1.1.7.
Can anyone lend me a helping hand?

Uh, you didn't define x, y, or value...maybe try defining those first? What pixel did you want to access?

im = Image.open("C:/Users/Owner/Desktop/bw.png")
x, y = 1, 2 #sample coordinates
print im.getpixel((x, y))
that should work, note that to getpixel method you pass one argument - a tuple

Related

How to convert list into DataFrame in Python (Binance Futures API)

Using Binance Futures API I am trying to get a proper form of my position regarding cryptocurrencies.
Using the code
from binance_f import RequestClient
request_client = RequestClient(api_key= my_key, secret_key=my_secet_key)
result = request_client.get_position()
I get the following result
[{"symbol":"BTCUSDT","positionAmt":"0.000","entryPrice":"0.00000","markPrice":"5455.13008723","unRealizedProfit":"0.00000000","liquidationPrice":"0","leverage":"20","maxNotionalValue":"5000000","marginType":"cross","isolatedMargin":"0.00000000","isAutoAddMargin":"false"}]
The type command indicates it is a list, however adding at the end of the code print(result) yields:
[<binance_f.model.position.Position object at 0x1135cb670>]
Which is baffling because it seems not to be the list (in fact, debugging it indicates object of type Position). Using PrintMix.print_data(result) yields:
data number 0 :
entryPrice:0.0
isAutoAddMargin:True
isolatedMargin:0.0
json_parse:<function Position.json_parse at 0x1165af820>
leverage:20.0
liquidationPrice:0.0
marginType:cross
markPrice:5442.28502271
maxNotionalValue:5000000.0
positionAmt:0.0
symbol:BTCUSDT
unrealizedProfit:0.0
Now it seems like a JSON format... But it is a list. I am confused - any ideas how I can convert result to a proper DataFrame? So that columns are Symbol, PositionAmt, entryPrice, etc.
Thanks!
Your main question remains as you wrote on the header you should not be confused. In your case you have a list of Position object, you can see the structure of Position in the GitHub of this library
Anyway to answer the question please use the following:
df = pd.DataFrame([t.__dict__ for t in result])
For more options and information please read the great answers on this question
Good Luck!
you can use that
df = pd.DataFrame([t.__dict__ for t in result])
klines=df.values.tolist()
open = [float(entry[1]) for entry in klines]
high = [float(entry[2]) for entry in klines]
low = [float(entry[3]) for entry in klines]
close = [float(entry[4]) for entry in klines]

Trying to import dictionary to work with from a url; 'unicode' object not callable

I'm new to coding and have searched as best I can to find out how to solve this before asking.
I'm trying to pull information from poloniex.com REST api, which is in JSon format I believe. I can import the data, and work with it a little bit, but when I try to call and use the elements in the contained dictionaries, I get "'unicode' object not callable". How can I use this information? The end goal with this data is to pull the "BTC: "(volume)" for each coin pair and test if it is <100, and if not, append it to a new list.
The data is presented like this or you can see yourself at https://poloniex.com/public?command=return24hVolume:
{"BTC_LTC":{"BTC":"2.23248854","LTC":"87.10381314"},"BTC_NXT":{"BTC":"0.981616","NXT":"14145"}, ... "totalBTC":"81.89657704","totalLTC":"78.52083806"}
And my code I've been trying to get to work with currently looks like this(I've tried to iterate the information I want a million different ways, so I dunno what example to give for that part, but this is how I am importing the data):
returnvolume = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=return24hVolume'))
coinvolume = json.loads(returnvolume.read())
coinvolume = dict(coinvolume)
No matter how I try to use the data I've pulled, I get an error stating:
"unicode' object not callable."
I'd really appreciate a little help, I'm concerned I may be approaching this the wrong way as I haven't been able to get anything to work, or maybe I'm just missing something rudimentary, I'm not sure.
Thank you very much for your time!
Thanks to another user, downshift, I have discovered the answer!
d = {}
for k, v in coinvolume.items():
try:
if float(v['BTC']) > 100:
d[k] = v
except KeyError:
d[k] = v
except TypeError:
if v > 100:
d[k] = k
This creates a new list, d, and adds every coin with a 'BTC' volume > 100 to this new list.
Thanks again downshift, and I hope this helps others as well!

Turtle bending lines

In the following code, the second box drawn gets messed up. It's almost like the lines aren't drawn straight up and down but at a slight angle. I've tried to make the sample MCVE.
import turtle, os
turtle.speed(0)
iOneAndHalve = 1.5 # Increasing to 1.501 makes a big difference
Q = 0
iSize = 80
def box(x):
for i in xrange(x):
turtle.forward(i+1)
turtle.left(90)
global Q
Q = i
box(iSize)
turtle.up()
turtle.forward(iOneAndHalve*Q) # <----------
turtle.down()
box(iSize)
os.system("pause")
If I set iOneAndHalve to 1.501 instead of 1.5, the problem is solved. The size of the box (and therefore Q doesn't seem to make a difference).
I have no clue why this does the trick and this smells like a cheap fix.
What's causing this (irratic) behaviour and how should I properly fix this?
Note: I realize the style of the coding is sub-standard. I'm afraid that's the result of MCVE'ing it.
It appears to be a problem with rounding, as replacing turtle.forward(iOneAndHalve*Q) with turtle.forward(round(iOneAndHalve * Q, 0)) fixes the problem.

Theano get unique values in a tensor

I have a tensor which I convert into a vector by flattening, now I want to remove the duplicate values in this vector. How can I do this? What is equivalent for numpy.unique() in theano?
x1 = T.itensor3('x1')
y1 = T.flatten(x1)
#z1 = T.unique() How do I do this?
For e.g. my tensor may be : [1,1,2,3,3,4,4,5,1,3,4]
and I want : [1,2,3,4,5]
EDIT: this is now available in Theano: http://deeplearning.net/software/theano/library/tensor/extra_ops.html#theano.tensor.extra_ops.Unique
This question was also asked on theano-user mailing list. The conclusion is that this is one of the function NumPy function that isn't wrapped in Theano. As he don't need the grad, it can be rapidly wrapped. Here is an example who expect the outputs to be the same as the input.
from theano.compile.ops import as_op
#as_op(itypes=[theano.tensor.imatrix],
otypes=[theano.tensor.imatrix])
def numpy_unique(a):
return numpy.unique(a)
More doc about as_op is available here: http://deeplearning.net/software/theano/tutorial/extending_theano.html#as-op-example

Error "'Quiver' object has no attribute 'shape'"

I am using the Python Quiver function to combine u-velocity and v-velocity values into a vector map. I have semi-successfully combined the two arrays by using the quiver function within the colormesh() function, and my code returns a B&W plot of the data, but I get an error message "'Quiver' object has no attribute 'shape'". The data plot also seems to not allow the landmass/ocean commands to plot (or if I put those commands before the colormesh() command, then the quiver() command doesn't work). Also, I can't seem to add color or size to the quiver arrows. Why am I still getting sort of successful plotting, if I'm getting this error message? How can I fix it? I tried making a quiver array and then just plotting the name of that in the colormesh(), but that didn't work, either.
Thank you!!
m = Basemap(llcrnrlon=-120,llcrnrlat=32,urcrnrlon=-116,urcrnrlat=35,
resolution='l',projection='stere',
lat_0=32.5,lon_0=-117.)
fig = plt.figure(figsize=(10,10))
plt.figtext(.45,.15,'Figure 1. Avg. velocity from CORDC HF Radar avg. June 1, 2013',fontsize=12,ha='center')
x, y = m(lon,lat)# define color map
cmap = plt.cm.hsv
cs = m.pcolormesh(x,y,quiver(lon[0:230],lat[0:230],u_nanmean_mask,v_nanmean_mask),shading='gouraud',cmap=cm.RdYlBu,vmin=-0.10,vmax=0.12)
m.drawcoastlines()
m.fillcontinents(color='#989865',lake_color='w')
m.drawmapboundary(fill_color='w')
m.drawparallels(np.arange(-80.,81.,5.),labels=[0,1,1,0])
m.drawmeridians(np.arange(-180.,180.,5.),labels=[1,0,0,1])