I'm trying to create a system for pattern matching in images and this is what I have currently:
def ratio(x,y):
return 1/(x*y)
def memory(image):
i__ia=0
l__img = Image.open(image)
l__pix = l__img.load()
l__width = l__img.width
l__height = l__img.height
s__img = None
l__r = 0
l__b = 0
l__g = 0
s__str = None
s__per = 0
for filename in os.listdir("Memory/"):
i__ia+=1
m__percent = 0
p__r = 0
p__g = 0
p__b = 0
f = os.path.join("Memory/", filename)
m__img = Image.open(f)
m__pix = m__img.load()
for l__w in range(0,l__width,1):
for l__h in range(0,l__height,1):
try:
if m__pix[l__w,l__h] == l__pix[l__w,l__h]:
temp = m__pix[l__w,l__h]
a__percent = ratio(l__width,l__height)
p__r+=temp[0]
p__g+=temp[1]
p__b+=temp[2]
m__percent+=a__percent
else:
p__r+=temp[0]
p__g+=temp[1]
p__b+=temp[2]
a__percent = ratio(l__width,l__height)
m__percent-=a__percent
except:
a__percent = ratio(l__width,l__height)
m__percent-=a__percent
pass
if m__percent > s__per and p__r >= l__r and p__b >= l__b and p__g >= l__g:
s__per = m__percent
s__img = m__img
s__str = f
l__r = (1/(p__r+p__b+p__g))*p__r
l__b = (1/(p__r+p__b+p__g))*p__b
l__g = (1/(p__r+p__b+p__g))*p__g
else:
m__percent = 0
if s__per > 0.8:
return True, s__per, s__str,l__r,l__g,l__b
else:
try:
tes = Image.open(image)
tes.save(f'Memory/unknown{i__ia}.png')
return False, s__per, s__str,l__r,l__g,l__b
except:
pass
My end goal is to find differences between pictures, find similarities, be able to classify the image based on how similar it is to other images.
Currently, all I've made is something that can tell how similar two images are based on their color differences and size differences.
I'm having trouble thinking of a way to detect if there is a similar shape or pattern in the image.
Any help is greatly appreciated!
Related
Can anyone tell me why I can only refer to the Checkbutton variable once? the important part of code is bold.
The first time that I use the variable it run, but the second, the same variable dont work. I think I tried very much but dont work!
def botao_executar():
botão_executar = comand of Button
if (pag1 <= numero_quadros):
img1 = cv.imread('imagemfinal.jpg')
novo_y_1 = int(num_novos_y*1)
crop_image_1 = img1[0:novo_y_1]
status = cv.imwrite('Desktop\ORC/crop_image1.png', crop_image_1)
q = 590
a = (q+220)
z = (q-590)
p = (q+250)
#Dimensoes_1
crop_image_1_1_dimensoes = crop_image_1[q+60:a-20, z:p]
status_dimensoes = cv.imwrite('Desktop\ORC/crop_image1.1_dimensoes.png', crop_image_1_1_dimensoes)
img_1_1_dimensoes = PIL.Image.open('Desktop\ORC/crop_image1.1_dimensoes.png')
pytesseract.pytesseract.tesseract_cmd =r'C:\Users\joaoccfaria\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
result_1_1_dimensoes = pytesseract.image_to_string(img_1_1_dimensoes, config='--psm 6 digits')
with open('abc.txt',mode ='w') as file:
file.write(result_1_1_dimensoes)
if v_dimensoes.get()> 0:
v_dimensoes.get= variable of checkbutton here it works!
print('dimensoes_1 = '+ result_1_1_dimensoes + ';')
sheet.write('A1', result_1_1_dimensoes)
else:
pass
pag2 = 2
if (pag2 <= numero_quadros):
img2 = cv.imread('imagemfinal.jpg')
novo_y_1 = int(num_novos_y*1)
crop_image_2 = img2[novo_y_1:novo_y_1*2]
status = cv.imwrite('Desktop\ORC/crop_image2.png', crop_image_2)
q = 590
a = (q+220)
z = (q-590)
p = (q+250)
#Dimensoes_2
crop_image_2_1_dimensoes = crop_image_2[q+60:a-20, z:p]
status_dimensoes = cv.imwrite('Desktop\ORC/crop_image2.1_dimensoes.png', crop_image_2_1_dimensoes)
img_2_1_dimensoes = PIL.Image.open('Desktop\ORC/crop_image2.1_dimensoes.png')
pytesseract.pytesseract.tesseract_cmd =r'C:\Users\joaoccfaria\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
result_2_1_dimensoes = pytesseract.image_to_string(img_2_1_dimensoes, config='--psm 6 digits')
with open('abc.txt',mode ='w') as file:
file.write(result_2_1_dimensoes)
if v_dimensoes.get()> 0:
here the same variable, but says that the name is not defined
print('dimensoes_2 = '+ result_2_1_dimensoes + ';')
sheet.write('A21', result_2_1_dimensoes)
else:
pass
Thanks in advance, any suggestion. Compliments.
So for my bot, I am first extracting data via api and storing it in csv. When I run my for loop on data via api, it gives no error and runs smoothly.
But when the csv file is read and run, it gives out of bound error.
This is my function to generate data:
full_list = pd.DataFrame(columns=("date","open","high","low","close","volume","ticker","RSI","ADX","20_sma","max_100"))
def stock_data(ticker):
create_data = fetchOHLC(ticker,'minute',60)
create_data["ticker"] = ticker
create_data["RSI"] = round(rsi(create_data,25),2)
create_data["ADX"] = round(adx(create_data,14),2)
create_data["20_sma"] = round(create_data.close.rolling(10).mean().shift(),2)
create_data["max_100"] = create_data.close.rolling(100).max().shift()
create_data.dropna(inplace=True,axis=0)
create_data.reset_index(inplace=True)
return create_data
stocklist = open("stocklist.txt","r+")
tickers = stocklist.readlines()
for x in tickers:
try:
full_list = full_list.append(stock_data(x.strip()))
except:
print(f'{x.strip()} did not work')
full_list.to_csv("All_Data")
full_list
So when I run the same code below on dataframe created I got no error. But when I run the same code on the csv file, I get out of bound error.
list_tickers = full_list["ticker"].unique()
for y in list_tickers[:2]:
main = full_list[full_list["ticker"]==y]
pos = 0
num = 0
tick = y
signal_time = 0
signal_rsi = 0
signal_adx = 0
buy_time = 0
buy_price = 0
sl = 0
#to add trailing sl in this.
for x in main.index:
maxx = main.iloc[x]["max_100"]
rsi = main.iloc[x]["RSI"]
adx = main.iloc[x]["ADX"]
sma = main.iloc[x]["20_sma"]
close = main.iloc[x]["close"]
high = main.iloc[x]["high"]
if rsi > 80 and adx > 35 and close > maxx:
if pos == 0:
buy_price = main.iloc[x+1]["open"]
buy_time = main.iloc[x+1]["date"]
pos=1
signal_time = main.iloc[x]["date"]
signal_rsi = main.iloc[x]["RSI"]
signal_adx = main.iloc[x]["ADX"]
elif close < sma:
if pos == 1:
sell_time = main.iloc[x]["date"]
sell_price = sma*.998
pos=0
positions.loc[positions.shape[0]] = [y,signal_time,signal_rsi,signal_adx,buy_time,buy_price,sell_time,sell_price]
Any idea why?
Here is a cleanup and file call code:
full_list = pd.read_csv("All_data")
full_list.dropna(inplace=True,axis=0)
full_list.drop(labels="Unnamed: 0",axis=1) < index of previous dataframe
full_list.head(5)
Thanks
I am trying to plot a decision tree using ID3 in Python. I am really new to Python and couldn't understand the implementation of the following code. I need to know how I can apply this code to my data.
from math import log
import operator
def entropy(data):
entries = len(data)
labels = {}
for feat in data:
label = feat[-1]
if label not in labels.keys():
labels[label] = 0
labels[label] += 1
entropy = 0.0
for key in labels:
probability = float(labels[key])/entries
entropy -= probability * log(probability,2)
return entropy
def split(data, axis, val):
newData = []
for feat in data:
if feat[axis] == val:
reducedFeat = feat[:axis]
reducedFeat.extend(feat[axis+1:])
newData.append(reducedFeat)
return newData
def choose(data):
features = len(data[0]) - 1
baseEntropy = entropy(data)
bestInfoGain = 0.0;
bestFeat = -1
for i in range(features):
featList = [ex[i] for ex in data]
uniqueVals = set(featList)
newEntropy = 0.0
for value in uniqueVals:
newData = split(data, i, value)
probability = len(newData)/float(len(data))
newEntropy += probability * entropy(newData)
infoGain = baseEntropy - newEntropy
if (infoGain > bestInfoGain):
bestInfoGain = infoGain
bestFeat = i
return bestFeat
def majority(classList):
classCount={}
for vote in classList:
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
def tree(data,labels):
classList = [ex[-1] for ex in data]
if classList.count(classList[0]) == len(classList):
return classList[0]
if len(data[0]) == 1:
return majority(classList)
bestFeat = choose(data)
bestFeatLabel = labels[bestFeat]
theTree = {bestFeatLabel:{}}
del(labels[bestFeat])
featValues = [ex[bestFeat] for ex in data]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
theTree[bestFeatLabel][value] = tree(split/(data, bestFeat, value),subLabels)
return theTree
So what I did after this is the following:
infile=open("SData.csv","r")
data=infile.read()
tree(data)
The error which I got is "1 argument is missing" which is the label which I have to define and this is where I don't know what I have to put. I tried the variable for which I have to make the decision tree but it doesn't work:
tree(data,MinTemp)
Here I get an error "MinTemp is not defined".
Please help me out and let me know what I should do to have a look at the tree.
Following is the part of data and I want to generate a tree for MinTemp
MinTemp,Rainfall,Tempat9,RHat9,CAat9,WSat9
high,no,mild,normal,overcast,weak
high,no,mild,normal,cloudy,weak
high,no,mild,normal,cloudy,mild
high,yes,mild,high,cloudy,weak
high,yes,mild,high,cloudy,mild
medium,yes,mild,high,cloudy,mild
high,no,mild,high,overcast,weak
high,no,mild,normal,sunny,weak
high,no,hot,normal,sunny,weak
high,no,hot,normal,overcast,weak
I have created a class, ParRec, that reads data from Par/Rec-files (binary images -> numpy-arrays), and now I want to add additional methods to the class to increase functionality, such as a method createFigure(self, ind) that would draw an image of the 2D-image at ind in the 3D-stack of images.
However, this doesn't work no matter how I try, I only get empty figures which are "not responding". There is nothing wrong with the data per se, because when I saved the array to outside the python script and did the exact same thing as in the createFigure-method it did work. These are the relevant parts of the code:
import numpy as np
import matplotlib.pyplot as plt
class ParRec():
def __init__(self, filename, equalResolution = True):
"""
This class is used to read and create a ParRec-object, which contains
arrays of parameters and the corresponding image matrix, in a similar way
to the IDL-struct system previously implemented.
Additionally, the class has several methods that can be called later to
simplify calculations, e.g. removePhaseImages and selectSlice.
filename - full pathname to the Par/Rec-files, without .extension
equalResolution - if set to false, ParRec-object collects parameters like
xres and yres in arrays, otherwise they are constants
and all images in the stack are assumed to be of equal
dimensions.
"""
self.slice_number = 0
self.echo_number = 0
self.dynamic_scan_number = 0
self.cardiac_phase_number = 0
self.image_type_mr = 0
self.scanning_sequence = 0
self.index_in_REC_file = 0 # (in images)
self.image_pixel_size = 0 # (in bits)
self.scan_percentage = 0
self.recon_resolution = 0 # (x y)
self.rescale_intercept = 0
self.rescale_slope = 0
self.scale_slope = 0
self.window_center = 0
self.window_width = 0
self.image_angulation = 0 # (ap,fh,rl in degrees)
self.image_offcentre = 0 # (3*float)
self.slice_thickness = 0 # (in mm)
self.slice_gap = 0 # (in mm)
self.image_display_orientation = 0
self.slice_orientation = 0 # (TRA/SAG/COR) = (1/2/3)
self.fmri_status_indication = 0
self.image_type_ed_es = 0 # (end diast/end syst)
self.pixel_spacing = 0 # (x y) (in mm)
self.echo_time = 0
self.dyn_scan_begin_time = 0
self.trigger_time = 0
self.diffusion_b_factor = 0
self.number_of_averages = 0
self.image_flip_angle = 0 # (in degrees)
self.cardiac_frequency = 0 # (bpm)
self.minimum_RR_interval = 0 # (in ms)
self.maximum_RR_interval = 0 # (in ms)
self.turbo_factor = 0 # (0=no turbo)
self.inversion_delay = 0 # (in ms)
self.diffusion_b_value_number = 0 # (imagekey!)
self.gradient_orientation_number = 0 # (imagekey!)
self.contrast_type = 0
self.diffusion_anisotropy_type = 0
self.diffusion = 0 # (ap, fh, rl)
self.label_type = None # (ASL) (imagekey!)
self.xres = 0
self.yres = 0
self.size = 0
self.equalResolution = equalResolution
# Read ParRec-files
self.readPar(filename)
self.readRec(filename)
# Get number of slices, dynamics, information about phase images etc.
self.getAdditionalData()
def readPar(self,filename)
...
def redRec(self,filename)
...
self.matrix = ...
def createFigure(self, ind):
img = self.matrix[:,:,ind].astype(np.float32)
fig = plt.figure()
plt.imshow(img, cmap = plt.cm.gray)
return fig
if __name__ == '__main__':
filename = '...\filename'
obj = ParRec(filename)
fig = obj.createFigure(0)
plt.show()
Can anybody explain what's going on? That is, why the image-drawing doesn't work when used as a class-method like this, and how to make it work?
EDIT: Inserted the init method, and managed to screw up the indentation a bit, but that is not a problem in the original code.
Best regards,
Mikael
This question already has answers here:
Is it possible to use ViBe algorithm, implemented in opencv, for systema without GPU?
(3 answers)
Closed 10 years ago.
i have these
codebook.py
#http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.148.9778&rep=rep1&type=pdf
import numpy as np
import cv2
alpha = 5
beta = 0.95
Tdel = 80
Tadd = 140
Th= 80
mn,mx,f,l,p,q=0,1,2,3,4,5
class CodeBook():
def __init__(self,h,w):
self.h = h
self.w = w
self.M = np.empty((h, w), dtype=np.object)
self.H = np.empty((h, w), dtype=np.object)
filler = np.frompyfunc(lambda x: list(), 1, 1)
filler(self.M,self.M)
filler(self.H,self.H)
self.t = 1
def updatev(self,gray,cb):
I,t = gray,self.t
if not cb:
c = [max(0.0,I-alpha),min(255.0,I+alpha),1,t-1,t,t]
cb.append(c)
else:
found = False
for cm in cb:
if(cm[mn]<=I<=cm[mx] and not found):
cm[mn] = ((I-alpha)+(cm[f]*cm[mn]))/(cm[f]+1.0)
cm[mx] = ((I+alpha)+(cm[f]*cm[mx]))/(cm[f]+1.0)
cm[f] += 1
#cm[l] = max(cm[l],t-cm[q])
cm[l] = 0
cm[q] = t
found = True
else:
cm[l] = max(cm[l],10-cm[q]+cm[p]-1)
if not found:
c = [max(0.0,I-alpha),min(255.0,I+alpha),1,t-1,t,t]
cb.append(c)
return cb
def update(self,gray):
h,w,M = self.h,self.w,self.M
updatev = np.vectorize(self.updatev,otypes=[np.object])
self.M=updatev(gray,M)
self.t += 1
def fgv(self,gray,cwm,cwh):
I,t = gray,self.t
pixval = 0
found = False
for cm in cwm:
if(cm[mn]<=I<=cm[mx] and not found):
cm[mn] = (1-beta)*(I-alpha) + (beta*cm[mn])
cm[mx] = (1-beta)*(I+alpha) + (beta*cm[mx])
cm[f] += 1
#cm[l] = max(cm[l],t-cm[q])
cm[l] = 0
cm[q] = t
found = True
else:
cm[l] += 1
#cm[l]=max(cm[l],t-cm[q]+cm[p]-1)
cwm[:] = [cw for cw in cwm if cw[l]<Tdel]
if found: return 0
for cm in cwh:
if(cm[mn]<=I<=cm[mx] and not found):
cm[mn] = (1-beta)*(I-alpha) + (beta*cm[mn])
cm[mx] = (1-beta)*(I+alpha) + (beta*cm[mx])
cm[f] += 1
#cm[l] = max(cm[l],t-cm[q])
cm[l] = 0
cm[q] = t
found = True
else:
#cm[l]=max(cm[l],t-cm[q]+cm[p]-1)
cm[l] += 1
if not found:
c = [max(0.0,I-alpha),min(255.0,I+alpha),1,0,t,t]
cwh.append(c)
cwh[:] = [cw for cw in cwh if cw[l]<Th]
tomove = [cw for cw in cwh if cw[f]>Tadd]
cwh[:] = [cw for cw in cwh if not cw in tomove]
cwm.extend(tomove)
return 255
def fg(self,gray):
h,w,M,H = self.h,self.w,self.M,self.H
fgv = np.vectorize(self.fgv,otypes=[np.uint8])
fg = fgv(gray,M,H)
self.t += 1
return fg
test.py
import cv2
import sys
import numpy as np
import time
import cProfile
import pyximport; pyximport.install(reload_support=True,
setup_args={'script_args':["--compiler=mingw32"]})
import codebook
c = cv2.VideoCapture(0)
c.set(3,320)
c.set(4,240)
cv2.namedWindow('vid',0)
cv2.namedWindow('fg',0)
_,img = c.read()
img = cv2.resize(img,(160,120))
h,w = img.shape[:2]
cb = codebook.CodeBook(h,w)
N=0
def fillholes(gray):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
res = cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)
def run():
while(1):
global N
_,img = c.read()
img = cv2.resize(img,(160,120))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('vid',gray)
if N < 10:
cb.update(gray)
else:
start = time.clock()
fg = cb.fg(gray)
print time.clock()-start
element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(2,2))
fg= cv2.erode(fg,element)
fillholes(fg)
cv2.imshow('fg',fg)
N += 1
if cv2.waitKey(5)==27:
break
run()
cv2.destroyAllWindows()
c.release()
the code is stuck # fgv. cython can speed it up somewhat. but it is still running slowly. i am thinking of doing either of the two
make it run in parallel
multithreading. i am using epd's numpy and changed the MKL_NUM_THREADS to 8. yet it is still bound to a single core.
distribute to worker processes array slices
redo some/all(which? i have no exp) parts in cpp although i really would like to avoid this
i have changed fgv as much as i know how. please let me know what should i be looking at next. thanks a lot!
fixed:
Is it possible to use ViBe algorithm, implemented in opencv, for systema without GPU?
more:http://www.changedetection.net/