how to load image cases to measure ROI? - python

I am trying to apply this code to get the cases I want to measure:
def get_cases(data_dir):
image_folders = os.listdir(data_dir)
image_folders = [f for f in image_f01ders if not f.startswith('.') and '.' not in f]
desired_cases = pd.read_exce1('data/df.xlsm')
desired_cases = desired_cases.query("vetting == 'Y'")
desired_image_ids = desired_cases['ID']
images_to_measure = []
for img in image_folders:
first_ = img.find('.')
if int(img[first_+1]) in desired_image_ids.unique():
images_to_measure.append
images_to_measure = [os.path.join(data_dir, f) for f in images_to_measure]
return images_to_measure
However, when I run this, it throws the following error,
cases = get_cases(data_dir)
File "measure.py", line 70, in get_cases
if int(img[first_+1]) in desired_image_ids.unique():
ValueError: invalid literal for int() with base 10: 'A'
Could someone explain to me why? And how to fix it? Does this have to do with the folder format? or how I find the img files?

the value that img[first_+1] returns is 'A'. it is likely that the number is in base 16. you should pass the number 16 as the 2nd argument to int function. (int(img[first_+1],16)). Doing so will convert the value to an integer from the base 16.
note that if the int function is called without the 2nd argument, it will take the number as a base 10.
if another error comes up, it is possible that something else is wrong.

Related

Converting list from string to int but there's a catch

I'll start off by saying that I don't know much about programming and I tried searching for answers but I didn't even know what to type in the search engine. So here goes.
class Point:
def __init__ (self, x, y):
self.x = x
self.y = y
def __str__ (self):
return "Members are: %s, %s" % (self.x, self.y)
I have this class which represents a point with its x and y coordinate.
I have a list points = [] and if I manually append a point to that list e.g. points.append(Point(-1.0, 3)) the output returns (-1.0, 3) I'm doing some calculations with these points but I don't think it matters if I put the code for that here.
Things get tricky because I have to input the numbers from a file. I already added them to another list and appended them using a loop. The problem is that the list is in str and if I convert it into int I get an error because of the decimal .0 It says in my assignment that I have to keep the same format as the input.
The thing I don't understand is how does it keep the decimal .0 when I input it like this points.append(Point(-1.0, 3)) and is it possible to get the same output format with numbers from a file.
I tried converting it to float but then all the coordinates get decimal places.
You can use this code to convert the inputs appropriately, with this try-catch mechanism, we first try int, then if we didn't successful, we continue with float.
def float_or_int(inp):
try:
n = int(inp)
except ValueError:
try:
n = float(inp)
except ValueError:
print("it's not int or float")
return n
input_1 = '10.3'
input_2 = '10.0'
input_3 = '10'
res1 = float_or_int(input_1)
res2 = float_or_int(input_2)
res3 = float_or_int(input_3)
print(res1, type(res1)) # 10.3 <class 'float'>
print(res2, type(res2)) # 10.0 <class 'float'>
print(res3, type(res3)) # 10 <class 'int'>
I don't know how your inputs stored in the file/another list you are reading, but you get the idea how to parse a single input.
You could use this:
proper_points = []
for x,y in points:
float_x = float(x)
int_y = int(y)
coords = proper_points.append((x,y))
For your calculations, you could use the proper_points list instead of points
Man, do not reinvent the wheel. If you need to import data from file you can use numpy for example and the function loadtxt. https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
I do not understand how your file is made and the format of the coordinate. In the bunch of code points.append(Point(-1.0, 3)) the first number is a float the second one is an integer. Which format do you want?
For example in file.dat you have the x,y positions:
1 1
2 3
4 5
where the first column is the x position and the second one represents y. Then you can use this code
import numpy as np
points = np.loadtxt('file.dat', dtype = 'int')
in points you have all the positions inside the file and you can just use slicing to access them.

int(), can't convert non-string with explicit base in python

there are two things I can't understand:
1-What does "non-string - with explicit base" means? is it like pointers?
2 How to solve it?
you can check the code and the error it appears on line 25 here. (it is clickable)
Error message:
dec_list.append(int(rmsg[x],2))
TypeError: int() can't convert non-string with explicit base
It's obvious I'm not a python guy but I'm trying to do smth from time to time.
my aaaa.txt file contains
01110001010100010101010001010101011001010110110101010101010101000001010110010101010000010101001001010010110101
local_file=open('aaaa.txt' , 'r', encoding = 'utf-8')
#1st checkpoint open and read the file
a=local_file.read()
n=10
i=0
msg=list() #create a blank list for lsb first
rmsg=list() #create a blank list for msb first
asciimsg=list() #create a blank list for decoded ASCII character
def swap(num):
str_num = str(num)
str_swapped = str_num[-1] +str_num[-2] + str_num[2:-2] + str_num[1] + str_num[0]
return int(str_swapped)
while (n<=len(a)):
# 3th cp: gets the 7 bit, lsb first in the aaaa.txt, one by one till the end
msg.append(a[i+1:n-2])
rmsg.append(swap(a[i+1:n-2]))
n=n+10
i=i+10
print('lsb first binary:')
print(msg)
print('msb first binary(ASCII):')
print(rmsg)
dec_list=list()
for x in range(len(rmsg)):
dec_list.append(int(rmsg[x],2)) #4th checkpoint: convert to decimal
print('ASCII in decimal:')
print(dec_list)
for z in dec_list:
asciimsg.append(chr(z)) #5th cp: use the chr function to convert to ascii
print(asciimsg)
shortmsg=""
for t in asciimsg:
shortmsg=shortmsg+t
print(shortmsg) #6th cp: printing the decoded msg
int is not a str, so convert it to a string first:
dec_list.append(int(str(rmsg[x]), 2))
It is much more Pythonic to use a list comprehension instead of a for-loop like that, though:
dec_list = [int(str(c), 2) for c in rmsg]
int() is a method used in python to convert numbers in the form of strings to integers, for example: "2" is a string, int("2") = 2 so now 2 is an integer, same for your case but the base case is that the initial form of the message is neither an integer nor a string so first you need to convert the message to a string using str(message) and then int(message), also put as int(str(message)).

Parsing a set of range of numbers

I wrote a simple code to find the intersection between two set of ranges and print the intersection. Now i am trying to write the result to a file. but i get an error saying write() argument must be str not set.
import numpy
# initialize A and B
filename = "set.txt"
f = open("set.txt", "w")
x = numpy.arange(4000, 5000, 1)
y = numpy.arange(3500, 5500, 1)
#x.intersection(y)
#print (set(x).intersection(y))
f.write(set(x).intersection(y))
f.close()
it works with print but i include the write it give that error
Your command must be 'str' type:
f.write(str(set(x).intersection(y)))

Reading input lines for int objects separated with whitespace?

I'm trying to solve a programming problem that involves returning a boolean for an uploaded profile pic, matching its resolution with the one that I provide as input and returning a statement that I've described below. This is one such test case that is giving me errors:
180
3
640 480 CROP IT
320 200 UPLOAD ANOTHER
180 180 ACCEPTED
The first line reads the dimension that needs to be matched, the second line represents the number of test cases and the rest comprise of resolutions with whitespace separators. For each of the resolutions, the output shown for each line needs to be printed.
I've tried this, since it was the most natural thing I could think of and being very new to Python I/O:
from sys import stdin, stdout
dim = int(input())
n = int(input())
out = ''
for cases in range(0, n):
in1 = int(stdin.readline().rstrip('\s'))
in2 = int(stdin.readline().rstrip('\s'))
out += str(prof_pic(in1, in2, dim))+'\n'
stdout.write(out)
ValueError: invalid literal for int() with base 10 : '640 480\n'
prof_pic is the function that I'm abstaining from describing here to prevent the post getting too long. But I've written in such a way that the width and height params both get compared with dim and return an output. The problem is with reading those lines. What is the best way to read such lines with differing separators?
You can try this it is in python 3.x
dimention=int(input())
t=int(input())
for i in range(t):
a=list(map(int,input().split()))
Instead of:
in2 = int(stdin.readline().rstrip('\s'))
you may try:
in2 = map( int, stdin.readline().split()[:2])
and you get
in2 = [640, 480]
You're calling readline. As the name implies, this reads in a whole line. (If you're not sure what you're getting, you should try printing it out.) So, you get something like this:
640 480 CROP IT
You can't call int on that.
What you want to do is split that line into separate pieces like this:
['640', '480', 'CROP IT']
For example:
line = stdin.readline().rstrip('\s')
in1, in2, rest = line.split(None, 2)
Now you can convert those first two into ints:
in1 = int(in1)
in2 = int(in2)

Binary To String Conversion

I'm relatively new to python and I'm trying to design a program that takes an input of Binary Data and Converts it to a String of Text. I have the following so far but keep getting the following error: TypeError: unsupported operand type(s) for &: 'str' and 'int' Can anyone see where I'm going wrong? And, if so, advise how to fix it?
a = int(input("please enter the binary you want to convert: "))
for str in a:
g = [~(chr(str)&~240)|(e&~240)]
f = 86
e = 231
d = bin(chr(str))
b = (str)
j=(b)
print(j)
There is quite a lot wrong with what you're doing; I'm not sure how you get the error you claim to have, given the other errors in the posted code. In order of reading the function:
Don't call your own variables str, it prevents you from accessing the built-in of the same name. Also, that variable either isn't a str, or causes a TypeError on chr(str).
You can't iterate over an integer for x in y:; this is also a TypeError.
(The error you report) chr(str) returns a string of length one. This is not a valid operand type for &, hence TypeError.
Another operand, e, has not yet been defined, so that will be a NameError.
Irrespective of that, you never use g again anyway.
Or f - what's that even for?
Now e is defined!
bin(chr(str)) will never work - again, chr returns a string, and bin takes a number as an argument.
b = (str) works, but the parentheses are redundant.
Same with j = (b), which is also not indented far enough to be in the loop.
Neither is print(j).
It is not clear what you are trying to achieve, exactly. If you gave example inputs (what format is the "Binary Data"?) and outputs (and what "String of Text" do you want to get?) along with your actual code and the full error traceback this might be easier.
Edit
With the information provided in your comment, it appears that you are trying to reverse these operations:
a = input("please enter the text you want to hide: ")
for ch in a:
## b = (ch) # this still doesn't do anything!
c = ord(ch)
## d = bin(c) # and d is never used
## e = 231 # e is only used to calculate g
f = 86
## g = (((c&240) >> 4)|(e&240)) # which is also never used
h = (((c&15)|(f&240)))
j = bin(h)
print(j)
This produces, for example (a == 'foo'):
0b1010110
0b1011111
0b1011111
However, to convert the input '0b1010110' to an integer, you need to supply int with the appropriate base:
>>> int('0b1010110', 2)
86
and you can't iterate over the integer. I think you want something like:
data = input("please enter the binary you want to convert: ")
for j in data.split():
h = int(j, 2)
...
where the input would be e.g. '0b1010110 0b1011111 0b1011111', or just do one at a time:
h = int(input(...), 2)
Note that, as the function is reversed, you will have to define f before trying to go back through the bitwise operation.

Categories