how to delete the same number of photos in mein dataset in python - deep-learning

Hi i use python and made a Dataframe of Food, which has 1000 photos for each food.
i wanna drop some pictures of food ex)ice_cream 100 pictures, omelette 100pictures... etc)
def get_df_from_file(path, is_valid):
img_df = pd.read_csv(path, delimiter='/', header=None, names=['label', 'name'])
# Append .jpg extension to all file names
img_df['name'] = img_df['label'].astype(str) + '/' + img_df['name'].astype(str) + '.jpg'
# Join extracted values and set is_valid
img_df['is_valid'] = is_valid
#img_df=img_df.loc[(img_df['label'] == 'ramen')]
return img_df
# Load the train set
train_df = get_df_from_file(path/'train.txt', False)
print(train_df.shape)
# Load the validation set
test_df = get_df_from_file(path/'test.txt', True)
print(test_df.shape)
# Concatenate train and test sets
image_df = pd.concat([train_df, test_df])
display(image_df.sample(10))
print(image_df.shape)
train_df0=train_df.loc[(train_df['label'] == df.label[0])]
drop_indices = np.random.choice(train_df0.index,50, replace=False)
train_df0 = train_df0.drop(drop_indices)
train_df1=train_df.loc[(train_df['label'] == df.label[1])]
drop_indices = np.random.choice(train_df1.index,50, replace=False)
train_df1 = train_df1.drop(drop_indices)
train_df2=train_df.loc[(train_df['label'] == df.label[2])]
drop_indices = np.random.choice(train_df2.index,50, replace=False)
train_df2 = train_df2.drop(drop_indices)
train_df3=train_df.loc[(train_df['label'] == df.label[3])]
drop_indices = np.random.choice(train_df3.index,50, replace=False)
train_df3 = train_df3.drop(drop_indices)
train_df4=train_df.loc[(train_df['label'] == df.label[4])]
drop_indices = np.random.choice(train_df4.index,50, replace=False)
train_df4 = train_df4.drop(drop_indices)
train_df5=train_df.loc[(train_df['label'] == df.label[5])]
drop_indices = np.random.choice(train_df5.index,50, replace=False)
train_df5 = train_df5.drop(drop_indices)
so 100 pictures each of 101category must be erased
i try to drop pictures of each dataframe but wenn i do this i should repeat this 100 times... how can i solve this problem with short syntax?

Related

The srcset= strings on the website are https links, but when I use selenium's driver.find('img')['srcset'], it gives me base64 strings

I'm trying to scrape images from a website. In the website's html code, the srcset sections exist and are of the form
srcset="https://...."
For example,
srcset="https://secure.img1-fg.wfcdn.com/im/80458162/resize-h300-w300%5Ecompr-r85/1068/106844956/Derry+84%2522+Reversible+Sectional.jpg 300w,https://secure.img1-fg.wfcdn.com/im/19496430/resize-h400-w400%5Ecompr-r85/1068/106844956/Derry+84%2522+Reversible+Sectional.jpg 400w,https://secure.img1-fg.wfcdn.com/im/75516274/resize-h500-w500%5Ecompr-r85/1068/106844956/Derry+84%2522+Reversible+Sectional.jpg 500w"
However, when I try to get these srcset link using selenium and beautiful soup, I get the following:
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
Moreover, every time the srcset fails to get a valid link, the string that it gets is always
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
I tried a bunch of different lines of code, but haven't had success with any of it. Here is the full code I currently have:
def get_info_from_product_link(product_link): #get the price and correctly filtered image link
info = dict()
driver = webdriver.Chrome('C:/Users/Brian/Downloads/chromedriver_win32/chromedriver.exe')
driver.implicitly_wait(200)
try:
driver.get(product_link)
soup = BeautifulSoup(driver.page_source, 'html.parser')
time.sleep(60)
image_carousel = soup.find_all('li', {"class" : "ProductDetailImageCarouselVariantB-carouselItem"})
print("Number of images in gallery: ", len(image_carousel))
#deal with captcha
while len(image_carousel) <= 0:
print("CAPTCHA ENCOUNTERED. FIX")
soup = BeautifulSoup(driver.page_source, 'html.parser')
image_carousel = soup.find_all('li', {"class" : "ProductDetailImageCarouselVariantB-carouselItem"})
time.sleep(30)
valid_image_links = []
highest_resolution_images = []
#get correct image links
#i = 1
for image_block in image_carousel:
try:
#print("image_block:")
#print(image_block)
#print("Image: ", i)
#i += 1
images = image_block.find('div', {"class" : "ImageComponent ImageComponent--overlay"})
#image_links = images.find('img').get_attribute('srcset').split(',')
print(images)
#driver.implicitly_wait(60)
#wait = WebDriverWait(images, 30)
#image_links = wait.until(EC.visibility_of_element_located((By.tagName, "img"))).get_attribute("srcset").split(',')
#image_links = wait.until(EC.text_to_be_present_in_element_value((By.tagName, 'img'), "https")).get_attribute("srcset").split(',')
#image_links = wait.until(EC.text_to_be_present_in_element_value((By.CSS_SELECTOR, "img [srcset*='https']"), "https")).get_attribute("srcset").split(',')
#image_links = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img[src*='https']"))).get_attribute("src").split(',')
images.implicitly_wait(30)
image_links = images.find_element_by_tag_name('img').get_attribute('srcset').split(',')
#"div[class='ajax_enabled'] [style='display:block']"
#image_links = images.find('img')['srcset'].split(',')
#print("Image links:")
#print(image_links)
#print("Number of links: ", len(image_links))
for link in image_links:
print(link)
for image_info in image_links:
image_link = image_info.split(" ")[0]
try:
if hasValidBackground(image_link) and hasValidSize(image_link):
valid_image_links.append(image_link)
else:
print("Invalid image size or background")
except:
print('ERROR when reading image: ' + image_link)
continue
if len(valid_image_links) > 0:
highest_resolution_images.append(valid_image_links[-1])
valid_image_links.clear()
except:
print("Error. Invalid image link.")
pass
#extract one link to a correctly filtered image
if len(highest_resolution_images) <= 0:
return -1
valid_image_link = highest_resolution_images[0];
info['img_url'] = valid_image_link
#get price information
standard_price_block = soup.find('div', {"class" : "StandardPriceBlock"})
base_price_block = standard_price_block.find('div', {"class" : "BasePriceBlock BasePriceBlock--highlight"})
if base_price_block is None:
base_price_block = standard_price_block.find('div', {"class" : "BasePriceBlock"})
base_price = base_price_block.find('span').text
#price_block = soup.find('span', {"class" : "notranslate"})
#base_price = standard_price_block.find('span').text
info['price'] = base_price
print(base_price)
#print(f"Image link: {image_link}\n")
#print(f"Link to product: {product_link}\n")
driver.close()
#browser.switch_to.window(browser.window_handles[0])
return info
except TimeoutException as e:
print("Page Load Timeout Occurred. Quitting...")
driver.close()
I was testing using this website:
https://www.wayfair.com/furniture/pdp/foundstone-derry-84-reversible-sectional-w001832490.html
My goal is to process each image in the image gallery/carousel and find one that has white background and has valid size of height >= 80 and width >= 80
I'm just starting to learn web scraping, so any help would be much appreciated!!

A value from template's form parameters is not passed in View

I have a student that is using django framework to build an app.
She has a template that contains a slider. The part of this form in the template is:
<form method="GET" enctype="multipart/form-data">
<div class="slidecontainer">
<input name="range" type="range" min="{{ beginframe }}" max="{{ endframe }}" onclick="sLider.oninput();" class="slider" id="range">
<p>Value: <span id="demo"></span></p>
<button type="button" class="button4" name="showframebtn" id="showframebtn" >Show frame</button>
</div>
<input type="hidden" name="fname1" value="{{video_path}}" style=" margin-top: 15px; margin-left: -45px;width: 410px; height: 40px;">
</form>
Next, she needs to handle the value of the slider and the {{video_path}} value. This is her code a function in views.py:
elif request.method == 'GET' and 'f' in request.GET:
if framenumber:
print(framenumber)
fname_1 = request.GET.get('fname1')
print("fname", fname_1)
However, the value of hidden input parameter is not passed. The value she gets is None.
Using the page source from the browser we can see that indeed the hidden parameter has a value.
<form method="GET" enctype="multipart/form-data">
<div class="slidecontainer">
<input name="range" type="range" min="1" max="11" onclick="sLider.oninput();" class="slider" id="range">
<p>Value: <span id="demo"></span></p>
<button type="button" class="button4" name="showframebtn" id="showframebtn" >Show frame</button>
</div>
<input type="hidden" name="fname1" value="C:/Users/Username/PycharmProjects/thesis/static/3/actual_video.avi" style=" margin-top: 15px; margin-left: -45px;width: 410px; height: 40px;">
</form>
Can you please help us on how to fix this? Is this due to the fact that she is using a button parameter?
Thank you in advance!
The full function code from views.py can be found here:
def video_analysis(request):
framenumber = request.GET.get('f', '')
print("framenumber ", framenumber)
global frame2
global tmp_path
global myfile
global filename
global img1
global img2
global video_table, motionFlow_table
video_table = []
angles =[]
motionFlow_table = []
video_table = np.empty([30, 400, 400, 3], np.dtype('uint8'))
motionFlow_table = np.empty([30, 400, 400, 3], np.dtype('uint8'))
times =0
if (request.session['doctor_id'] == ""):
return redirect('login')
times = times +1
path = STATIC_PATH
direct = request.session['directory']
p_id = request.session['p_id']
p_name = request.session['p_name']
p_lastname = request.session['p_lastname']
os.chdir(direct)
print(direct)
myfile = None
if request.method == 'POST' and 'myfile' in request.FILES:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = myfile.name
print(filename)
if (not os.path.exists(direct + "\\" + myfile.name)):
filename = fs.save(direct + "\\" + myfile.name, myfile)
print(filename)
path = direct + "\\" + myfile.name
print(path)
print(direct)
request.session['path'] = path
request.session['file'] = myfile.name
print(myfile.name)
uploaded_file_url = fs.url(filename) + "/static"
print(uploaded_file_url)
if request.session.has_key('path'):
path = request.session['path']
tmp_path = ""
for i in range(0, len(path)):
if (path[i] == "\\"):
tmp_path = tmp_path + '/'
else:
tmp_path = tmp_path + path[i]
print(tmp_path)
print(myfile)
if myfile != None:
print("not empty")
cap = cv2.VideoCapture(str(myfile))
if (cap.isOpened() == False):
print("Error opening video")
begin_frame = 1
count =1 #counter for frames
ret, frame1 = cap.read()
# Region of Interest - ROI
template = frame1[150:250,0:100]
video_table[count] = frame1 # save the video into array
cv2.imwrite(('frame %d.jpg' % count), frame1)
original = frame1
grayimg_1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
cv2.imwrite('frame1gray.jpg', grayimg_1)
gray_img, topleft, bottomright = template_matching(grayimg_1,template )
print("topleft",topleft)
print("bottomright",bottomright)
cv2.imwrite("gray1.jpeg", grayimg_1)
if np.shape(frame1) == ():
print ("empty frame")
hsv = np.zeros_like(frame1)
hsv[..., 1] = 255
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
fourcc1 = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('output.avi', fourcc, 25.0, (500, 400))
out1 = cv2.VideoWriter('output1.avi', fourcc1, 25.0, (500, 400))
while (cap.isOpened()):
ret, frame2 = cap.read()
count =count+1
if ret != True:
break;
video_table[count] = frame2 # save video frames into table
cv2.imwrite(('frame %d.jpg' % count), frame2)
grayimg_2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray %d.jpeg", grayimg_2)
gray_img, topleft, bottomright = template_matching(grayimg_2, template)
# Computes a dense optical flow using the Gunnar Farneback's algorithm.
flow = cv2.calcOpticalFlowFarneback(grayimg_1, grayimg_2, None, 0.5, 3, 15, 3, 5, 1.2, 0)
test_img = draw_flow(gray_img, flow,topleft,bottomright)
cv2.imwrite(("motionFlow_img %d.jpg" %count), motionFlow_table[count])
# Calculate the magnitude and angle of 2D vectors.
mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
angles.append(ang)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cv2.imwrite('opticalfb.jpeg', frame2)
grayimg_1 = grayimg_2
print("number of frames: ", count)
out.release()
out1.release()
cv2.destroyAllWindows()
cv2.waitKey(0) #press something to continue
end_frame = count
# Video Properties
# number of frames
video_length = cap.get(cv2.CAP_PROP_FRAME_COUNT)
total_frames = int(video_length)
print("total" , total_frames)
#frame rate
frame_rate = float(cap.get(cv2.CAP_PROP_FPS))
print(frame_rate)
#video duration
duration = round(float(video_length / frame_rate), 2)
print(duration)
data = np.array(ang)
name_of_file1 = filename.split("/")[-1]
name_of_file1 = p_id + "/" + "frame 1.jpg"
print(name_of_file1)
return render(request, 'video_analysis.html', { 'video_frame' : name_of_file1,
'firstframe' : name_of_file1,
'video': myfile,
'video_path':tmp_path,
'beginframe': int(begin_frame),
'endframe': int(end_frame),
'video_duration': duration})
The issue I think is that you have method="GET" set on your form, but you're encoding the form as multipart/form-data. Data encoded as multipart/form-data is split into multiple parts and cannot be sent in the URL using GET.
If you want the form to make a GET request, then you should remove the enctype="multipart/form-data from the form. This will cause the form to send the data using the default encoding which can be sent in the URL.
Alternatively, if you wish to use multipart/form-data you should change the form method to method="POST". If you do that, you'll also need to modify your view:
elif request.method == 'POST' and 'f' in request.POST:
...
fname_1 = request.POST.get('fname1')

Object of type 'closure' is not subsettable - R

I am using R to extract tweets and analyse their sentiment, however when I get to the lines below I get an error saying "Object of type 'closure' is not subsettable"
scores$drink = factor(rep(c("east"), nd))
scores$very.pos = as.numeric(scores$score >= 2)
scores$very.neg = as.numeric(scores$score <= -2)
Full code pasted below
load("twitCred.Rdata")
east_tweets <- filterStream("tweetselnd.json", locations = c(-0.10444, 51.408699, 0.33403, 51.64661),timeout = 120, oauth = twitCred)
tweets.df <- parseTweets("tweetselnd.json", verbose = FALSE)
##function score.sentiment
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
# Parameters
# sentences: vector of text to score
# pos.words: vector of words of postive sentiment
# neg.words: vector of words of negative sentiment
# .progress: passed to laply() to control of progress bar
scores = laply(sentences,
function(sentence, pos.words, neg.words)
{
# remove punctuation
sentence = gsub("[[:punct:]]", "", sentence)
# remove control characters
sentence = gsub("[[:cntrl:]]", "", sentence)
# remove digits?
sentence = gsub('\\d+', '', sentence)
# define error handling function when trying tolower
tryTolower = function(x)
{
# create missing value
y = NA
# tryCatch error
try_error = tryCatch(tolower(x), error=function(e) e)
# if not an error
if (!inherits(try_error, "error"))
y = tolower(x)
# result
return(y)
}
# use tryTolower with sapply
sentence = sapply(sentence, tryTolower)
# split sentence into words with str_split (stringr package)
word.list = str_split(sentence, "\\s+")
words = unlist(word.list)
# compare words to the dictionaries of positive & negative terms
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
# get the position of the matched term or NA
# we just want a TRUE/FALSE
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
# final score
score = sum(pos.matches) - sum(neg.matches)
return(score)
}, pos.words, neg.words, .progress=.progress )
# data frame with scores for each sentence
scores.df = data.frame(text=sentences, score=scores)
return(scores.df)
}
pos = readLines(file.choose())
neg = readLines(file.choose())
east_text = sapply(east_tweets, function(x) x$getText())
scores = score.sentiment(tweetseldn.json, pos, neg, .progress='text')
scores()$drink = factor(rep(c("east"), nd))
scores()$very.pos = as.numeric(scores()$score >= 2)
scores$very.neg = as.numeric(scores$score <= -2)
# how many very positives and very negatives
numpos = sum(scores$very.pos)
numneg = sum(scores$very.neg)
# global score
global_score = round( 100 * numpos / (numpos + numneg) )
If anyone could help with as to why I'm getting this error it will be much appreciated. Also I've seen other answeres about adding '()' when referring to the variable 'scores' such as scores()$.... but it hasn't worked for me. Thank you.
The changes below got rid of the error:
x <- scores
x$drink = factor(rep(c("east"), nd))
x$very.pos = as.numeric(x$score >= 2)
x$very.neg = as.numeric(x$score <= -2)

tictactoe iteration issue. Function error

I am new to programming (About 2 months in to teaching myself). I am attempting to create a game of tic tac toe and use it as an opportunity to practice using functions and passing parameters.
I have got most of what I want to work working (for now I will add AI and a computer opponent) but when one of the human players win the endgame() function is called but it does not work as expected. It calls itself somehow and you have got to say N to end the game three times before the program is terminated. I am unable to see the wood for the trees on this one folks so help would be appreciated.
I know some of my coding will not be great so no trolling please.
Thanks
Shaun
def start():
choices = [" "," "," "," "," "," "," "," "," "]
while checkwin(choices)==False:
board(choices)
getchoice(choices)
def board(choices):
print("+---+---+---+")
print("+ "+choices[0]+" + "+choices[1]+" + "+choices[2]+" +")
print("+---+---+---+")
print("+ "+choices[3]+" + "+choices[4]+" + "+choices[5]+" +")
print("+---+---+---+")
print("+ "+choices[6]+" + "+choices[7]+" + "+choices[8]+" +")
print("+---+---+---+")
def endgame(winner):
print("The winner is "+ winner)
playagain=input("Another game? Y/N")
playagain = playagain.upper()
if playagain == "N":
print("Thanks, hope to see you again soon.")
else:
start()
def getchoice(choices):
userchoice = int(input ("Where would you like to put your X?"))
index = userchoice-1
while choices[index]!=" ":
userchoice = int(input ("That space is taken. Where would you like to put your X?"))
index = userchoice-1
choices[index]="X"
board(choices)
if checkwin(choices)==False:
userchoice = int(input ("Where would you like to put your O?"))
index = userchoice-1
while choices[index]!=" ":
userchoice = int(input ("That space is taken. Where would you like to put your O?"))
index = userchoice-1
choices[index]="O"
checkwin(choices)
return choices
def checkwin (c):
if checkwin1(c)==False:
if checkwin2 (c)==False:
return False
else:
endgame("Player 2")
else:
endgame("Player 1")
def checkwin1(c):
return ((c[0]=="X" and c[1]=="X" and c[2]=="X") or
(c[3]=="X"and c[4]=="X" and c[5] =="X") or
(c[6]=="X"and c[7]=="X" and c[8] =="X") or
(c[0]=="X"and c[3]=="X" and c[6] =="X" )or
(c[1]=="X"and c[4]=="X" and c[7] =="X") or
(c[2]=="X"and c[5]=="X" and c[8] =="X") or
(c[0]=="X"and c[4]=="X" and c[8] =="X") or
(c[6]=="X"and c[4]=="X" and c[2] =="X"))
def checkwin2(c):
return ((c[0]=="O" and c[1]=="O" and c[2]=="O") or
(c[3]=="O"and c[4]=="O" and c[5] =="O") or
(c[6]=="O"and c[7]=="O" and c[8] =="O") or
(c[0]=="O"and c[3]=="O" and c[6] =="O" )or
(c[1]=="O"and c[4]=="O" and c[7] =="O") or
(c[2]=="O"and c[5]=="O" and c[8] =="O") or
(c[0]=="O"and c[4]=="O" and c[8] =="O") or
(c[6]=="O"and c[4]=="O" and c[2] =="O"))
start()
Let's imagine that X wins (because this is probably what caused it to "end") three times.
You then get to if checkwin(choices)==False: within getchoice(),
'checkwin()' happily calls endgame(). endgame() returns, and then getchoice() continues executing.
At the end of getchoice(), checkwin() is called again, with the same result.
After getchoice() returns we get back to while checkwin(choices)==False: within start(), once again with the same result.
Also note that you will see this happening even more times if you actually played multiple games in a row.
Also try making O win, I think you will only have to say no to your prompt twice in that case.
EDIT:
class TicTacToeGame:
INCOMPLETE = 0
WINNER_PLAYER_1 = 1
WINNER_PLAYER_2 = 2
DRAW = 3
SYMBOLS=["X","O"," "]
def __init__(self,player_1, player_2):
self.board = [[-1]*3,[-1]*3,[-1]*3]
self.players = [player_1,player_2]
self.current_turn = 0;
def advance(self):
if self.calcGameState() != TicTacToeGame.INCOMPLETE:
return
while True:
x,y = self.players[self.current_turn].getMove();
if x < 0 or x > 2 or y < 0 or y>2 :
continue
if self.board[y][x] == -1:
break
self.board[y][x] = self.current_turn
self.current_turn += 1
self.current_turn %= 2
def stringify(self):
re = ""
fr = True
for row in self.board:
if fr:
fr=False
else:
re+= "\n" + "---+" * 2 + "---\n"
fe = True
for el in row :
if fe:
fe = False;
else:
re += "|"
re += " " + TicTacToeGame.SYMBOLS[el] + " "
return re
def calcGameState(self):
for i in range(0,3):
#col
if all(self.board[i][j] == self.board[i][0] for j in range(0,3)) and self.board[i][0] != -1:
return self.board[i][0] + 1
#row
if all(self.board[j][i] == self.board[0][i] for j in range(0,3)) and self.board[0][i] != -1:
return self.board[0][i] + 1
if all(self.board[i][i] == self.board[0][0] for i in range(0,3)) and self.board[0][0] != -1:
return self.board[0][0] + 1
if all(self.board[i][2-i] == self.board[0][2] for i in range(0,3)) and self.board[0][2] != -1:
return self.board[0][2] + 1
if all(self.board[i][j] != -1 for i in range(0,3) for j in range(0,3)):
return TicTacToeGame.DRAW
return TicTacToeGame.INCOMPLETE
def stringResult(self):
res = self.calcGameState()
if res == TicTacToeGame.INCOMPLETE:
return "Incomplete"
if res == TicTacToeGame.DRAW:
return "Draw"
return "Player " + self.SYMBOLS[res-1] + " Won!"
class HumanPlayer:
def __init__(self):
self.board = None
def setGame(self,game):
self.game = game
def getMove(self):
print(self.game.stringify())
print("Current turn is: " + self.game.SYMBOLS[self.game.current_turn])
print("enter row for move")
y = input()
print("enter col for move")
x = input()
return int(x)-1,int(y)-1
def playAgain():
playagain=input("Another game? Y/N\n > ")
playagain = playagain.upper()
if playagain == "N":
print("Thanks, hope to see you again soon.")
return False
return True
while True:
p = HumanPlayer()
t = TicTacToeGame(p,p)
p.setGame(t)
while t.calcGameState() == TicTacToeGame.INCOMPLETE:
t.advance()
print(t.stringResult())
if not playAgain():
break;

MatLab Save image to database using database toolbox

Is it possible to insert or save an image to a database table using MatLab?
Here's my code:
%Code for Database Login
conn = database('vlmsystem','admin','vlog');
indata = imread('C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\images database\auto1.jpg');
a = getframe(h);
indata = a.cdata;
hgsave(h, 'tempfile.fig')
fid = fopen('tempfile.fig', 'r')
indata = fread(fid, inf, '*uint8')
fclose(fid)
s = size(indata);
bdata = reshape(indata,[],1);
x = conn.Handle
StatementObject = x.preparestatement(insertcommand);
StatementObject.setObject(1,bdata)
StatementObject.execute
close(StatementObject)
dbpath = 'C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\vlogdbase.mdb';
tableName = 'vehicleLog';
colnames = {'date_time','plate_number','login_logout','physical_feature'}
colnames1 = {'date_time'}
colnames2 = {'plate_number'}
colnames3 = {'login_logout'}
colnames4 = {'physical_feature'}
dat = datestr(now);
pltno = (f);
lilo = 'login';
physf = {bdata}
coldata = {dat,pltno,lilo,}
insert(conn,tableName,colnames,coldata);
close(conn);
And I am getting this error.
Error using graphicsversion Input was not a valid graphics object
Error in getframe (line 50) usingMATLABClasses =
~graphicsversion(parentFig, 'handlegraphics');
Error in licenseplate>StartKnop_Callback (line 248) a = getframe(h);
Tried copying this solution but I can't seem to make it work. Here's the link.
EDIT: Fix Code....but... how to insert binary data into the database.
There's no binary option in the database. The result won't feed into the table.
%Code for Database Login
conn = database('vlmsystem','admin','vlog');
indata = imread('C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\images database\auto1.jpg');
s = size(indata);
bdata = reshape(indata,[],1);
dbpath = 'C:\Users\Sony Vaio\Documents\Task\0.1 Systems\System 1 - edited\Appendix\vlogdbase.mdb';
tableName = 'vehicleLog';
colnames = {'date_time','plate_number','login_logout','physical_feature'}
colnames1 = {'date_time'}
colnames2 = {'plate_number'}
colnames3 = {'login_logout'}
colnames4 = {'physical_feature'}
dat = datestr(now);
pltno = (f);
lilo = 'login';
physf = {bdata}
coldata = {dat,pltno,lilo,physf}
insert(conn,tableName,colnames,coldata);
close(conn);
Please read what you are copying.
The solution says:
Alternatively, if you have a figure and want to save a snapshot of it, use the command below:
You copied both blocks, one that reads files, one hat uses getframe to read a frame from a handle.