Procedure on adding image pixel data in a file in newline? - python-3.x

import cv2
import numpy as np
import os
k=[]
file1=open("TextData.txt",'w')
fn=input("Enter filename : ")
img=cv2.imread(fn,cv2.IMREAD_GRAYSCALE)
l=len(img)
w=len(img[0])
print(str(l)+"\n"+str(w))
for i in range(len(img)):
for j in range(len(img[0])):
k.append(img[i,j])
for a in range(len[k]):
file1.write(str(k[a])+"\n")
file1.close()
Basically, I'm running into the error :
Traceback (most recent call last):
File "imagereads.py", line 17, in <module>
for a in range(len[k]):
TypeError: 'builtin_function_or_method' object is not subscriptable
I'm trying to write a program that will store each image data in a file and access that later on when needed. Can anyone help me in this ? I'm doing this so that I can directly use file1.readLines() to read each data later on.
At first I tried appending each element to k, converting to a string and storing it directly. But I'm having problems getting back the data from the file into a list. Any help on this matter too will be appreciated.

Related

Howto read odata into pandas with python

I'm trying to load odata into
This is my code:
import pandas as pd
import pyodata
import requests
SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/'
HTTP_LIB = requests.Session()
northwind = pyodata.Client(SERVICE_URL, HTTP_LIB)
df = pd.DataFrame(northwind)
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\KrestenSkovstedBuch\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\frame.py", line 730, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
I think I need something in between my pyodata object and my DataFrame.
What would that be?
It needs to be some your own code :)
You are passing northwind, which is Pyodata.Client class to DataFrame constructor, which, well, expects something else. You must query your odata service using pyodata and then use the returned data structure (JSON probably) to initialize the Pandas DataFrame correctly, this is a more generic and already answered problem.

How can I remove Attribute error from my Csv program showing? [duplicate]

So I copied and pasted a demo program from the book I am using to learn Python:
#!/usr/bin/env python
import csv
total = 0
priciest = ('',0,0,0)
r = csv.reader(open('purchases.csv'))
for row in r:
cost = float(row[1]) * float(row[2])
total += cost
if cost == priciest[3]:
priciest = row + [cost]
print("You spent", total)
print("Your priciest purchase was", priciest[1], priciest[0], "at a total cost of", priciest[3])
And I get the Error:
Traceback (most recent call last):
File "purchases.py", line 2, in <module>
import csv
File "/Users/Solomon/Desktop/Python/csv.py", line 5, in <module>
r = csv.read(open('purchases.csv'))
AttributeError: 'module' object has no attribute 'read'
Why is this happening? How do I fix it?
Update:
Fixed All The Errors
Now I'm getting:
Traceback (most recent call last):
File "purchases.py", line 6, in <module>
for row in r:
_csv.Error: line contains NULL byte
What was happening in terms of the CSV.py:
I had a file with the same code named csv.py, saved in the same directory. I thought that the fact that it was named csv .py was screwing it up, so I started a new file called purchases.py, but forgot to delete csv
Don't name your file csv.py.
When you do, Python will look in your file for the csv code instead of the standard library csv module.
Edit: to include the important note in the comment: if there's a csv.pyc file left over in that directory, you'll have to delete that. that is Python bytecode which would be used in place of re-running your csv.py file.
There is a discrepancy between the code in the traceback of your error:
r = csv.read(open('purchases.csv'))
And the code you posted:
r = csv.reader(open('purchases.csv'))
So which are you using?
At any rate, fix that indentation error in line 2:
#!/usr/bin/env python
import csv
total = 0
And create your csv reader object with a context handler, so as not to leave the file handle open:
with open('purchases.csv') as f:
r = csv.reader(f)

"RuntimeWarning: invalid value encountered in double_scalars" error occurs when taking cube root in python3

from numpy import cos
from tabulate import tabulate
def f(x):
return (cos(x))**(1./3)
table=[i for i in range(50)]
table2=[]
for i in range(50):
table2.append(f(i))
tables=[table, table2]
print (tabulate(tables))
When I run this code, it gives me a weird error. I looked up on the net some but they were all related to zero division. My problem occurs at numpy.cos when I used it before without "root" operation it worked fine. It also returns an error about tabulate as "'int' object is not iterable" which I really dont get it why?. Here is the error:
limit.py:5: RuntimeWarning: invalid value encountered in double_scalars
return cos(x)**(1/3)
Traceback (most recent call last):
File "limit.py", line 12, in <module>
print (tabulate(table, table2))
File "/home/yav/anaconda3/lib/python3.6/site-packages/tabulate.py", line 1247, in tabulate
tabular_data, headers, showindex=showindex)
File "/home/yav/anaconda3/lib/python3.6/site-packages/tabulate.py", line 933, in _normalize_tabular_data
rows = list(map(list,rows))
TypeError: 'int' object is not iterable
I am just a beginner, so if you can explain more simpler, will be appreciated. Thank you very much

Specify where to save image taken with webcame Python

So I have a Python application that accesses the built-in webcam on a laptop and takes a picture. But I'm having difficulty specifying the storage location for the picture (in this case on the desktop). The code I have so far is:
import cv2
import time
import getpass
import os
getUser = getpass.getuser()
save = 'C:/Users/' + getUser + "/Desktop"
camera_port = 0
camera = cv2.VideoCapture(camera_port)
time.sleep(0.1)
return_value, image = camera.read()
os.path.join(cv2.imwrite(save, "user.png", image))
del camera
But when I run it I get the following error:
Traceback (most recent call last):
File "C:/Users/RedCode/PycharmProjects/MyApps/WebcamPic.py", line 13, in <module>
os.path.join(cv2.imwrite(save, "user.png", image))
TypeError: img is not a numpy array, neither a scalar
How can I specify where to store the image when it is taken?
This line here is where you have a problem.
os.path.join(cv2.imwrite(save, "user.png", image))
You want to do this
cv2.imwrite(os.path.join(save, "user.png"), image)
imwrite expects two arguments the file name and the image to be saved.
The call to os.path.join is building your saved file path.

AttributeError: 'str' object has no attribute 'dispersion_plot' NLTK

I am trying to create a dispersion_plot using NLTK. As far as I can tell, I am following the directions. When I run their example calling the example text that comes with NLTK it works. When I call my own text file, it has the above error.
mine:
>>> text11 = "Text_test.txt"
>>> text11.dispersion_plot(["semiosis", "dialectic", "essentially", "icon", "logo"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'dispersion_plot'
Their example code:
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])
Thankful for any advice/help!
Note that you have to make it into an NLTK Text object after tokenizing it. Also, your text11 variable as used in your code is the string "Text_test.txt", not the text inside the file called Text_test.txt.
Assuming that
you have matplotlib and numpy installed, which are necessary for dispersion_plot to work
your file is at /home/myfile.txt
your file is simple text like the ones they use
then this should do it
# from Ch. 3
f=open('/home/myfile.txt','rU') # open the file
raw = f.read() # read the text
tokens = nltk.word_tokenize(raw) # tokenize it
mytext = nltk.Text(tokens) # turn text into a NLTK Text object
# from Ch. 1
mytext.dispersion_plot(["semiosis", "dialectic", "essentially", "icon", "logo"])

Resources