Odoo 10, To display Default Image - odoo-10

How to display a default image (saved in /my_module/static/img/car1.png) in a form ?
I have a binary field like this:
car_image =field.Binary(string="car1",default=??)
in xml, i gave like this:
Please help

You can refer _get_default_image in res.partner.py
#api.model
def _get_default_image(self, partner_type, is_company, parent_id):
if getattr(threading.currentThread(), 'testing', False) or self._context.get('install_mode'):
return False
colorize, img_path, image = False, False, False
if partner_type in ['other'] and parent_id:
parent_image = self.browse(parent_id).image
image = parent_image and base64.b64decode(parent_image) or None
if not image and partner_type == 'invoice':
img_path = get_module_resource('base', 'static/src/img', 'money.png')
elif not image and partner_type == 'delivery':
img_path = get_module_resource('base', 'static/src/img', 'truck.png')
elif not image and is_company:
img_path = get_module_resource('base', 'static/src/img', 'company_image.png')
elif not image:
img_path = get_module_resource('base', 'static/src/img', 'avatar.png')
colorize = True
if img_path:
with open(img_path, 'rb') as f:
image = f.read()
if image and colorize:
image = tools.image_colorize(image)
return tools.image_resize_image_big(base64.b64encode(image))
Create function
#api.model
def create(self, vals):
if vals.get('website'):
vals['website'] = self._clean_website(vals['website'])
if vals.get('parent_id'):
vals['company_name'] = False
# compute default image in create, because computing gravatar in the onchange
# cannot be easily performed if default images are in the way
if not vals.get('image'):
vals['image'] = self._get_default_image(vals.get('type'), vals.get('is_company'), vals.get('parent_id'))
tools.image_resize_images(vals)
partner = super(Partner, self).create(vals)
partner._fields_sync(vals)
partner._handle_first_contact_creation()
return partner
Hope this will help you.

Related

TensorFlow training gets slower every batch

I am new to TensorFlow and I get my code running successfully by modifying tutorials from the official website.
I checked some other answers on StackOverflow, which says my problem is likely due to something is being added to the graph every time. However, I have no idea where to look for the code that might have caused this.
Also, I used tf.py_function to map the dataset because I really need to enable eagerly mode in the mapping.
def get_dataset(data_index):
# data_index is a Pandas Dataframe that contains image/label pair info, each row is one pair
data_index = prepare_data_index(data_index)
# shuffle dataframe here because dataset.shuffle is taking very long time.
data_index = data_index.sample(data_index.shape[0])
path = path_to_img_dir
# list of dataframe indices indicating rows that are going to be included in the dataset for training.
indices_ls = ['{}_L'.format(x) for x in list(data_index.index)] + ['{}_R'.format(x) for x in list(data_index.index)]
# around 310k images
image_count = len(indices_ls)
list_ds = tf.data.Dataset.from_tensor_slices(indices_ls)
# dataset.shuffle is commented out because it takes too much time
# list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)
val_size = int(image_count * 0.2)
train_ds = list_ds.skip(val_size)
val_ds = list_ds.take(val_size)
def get_label(index):
index = str(np.array(index).astype(str))
delim = index.split('_')
state = delim[1]
index = int(delim[0])
if state == 'R':
label = data_index.loc[index][right_labels].to_numpy().flatten()
elif state == 'L':
label = data_index.loc[index][left_labels].to_numpy().flatten()
return tf.convert_to_tensor(label , dtype=tf.float16)
def get_img(index):
index = str(np.array(index).astype(str))
delim = index.split('_')
state = delim[1]
index = int(delim[0])
file_path = '{}_{}.jpg'.format(data_index.loc[index, 'sub_folder'],
str(int(data_index.loc[index, 'img_index'])).zfill(4)
)
img = tf.io.read_file(os.path.join(path, file_path))
img = tf.image.decode_jpeg(img, channels=3)
full_width = 320
img = tf.image.resize(img, [height, full_width])
# Crop half of the image depending on the state
if state == 'R':
img = tf.image.crop_to_bounding_box(img, offset_height=0, offset_width=0, target_height=height,
target_width=int(full_width / 2))
img = tf.image.flip_left_right(img)
elif state == 'L':
img = tf.image.crop_to_bounding_box(img, offset_height=0, offset_width=int(full_width / 2), target_height=height,
target_width=int(full_width / 2))
img = tf.image.resize(img, [height, width])
img = tf.keras.preprocessing.image.array_to_img(
img.numpy(), data_format=None, scale=True, dtype=None
)
# Apply auto white balancing, output an np array
img = AWB(img)
img = tf.convert_to_tensor(img, dtype=tf.float16)
return img
def process_path(index):
label = get_label(index)
img = get_img(index)
return img, label
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.map(lambda x: tf.py_function(
process_path,
[x], (tf.float16, tf.float16)), num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(lambda x: tf.py_function(
process_path,
[x], (tf.float16, tf.float16)), num_parallel_calls=AUTOTUNE)
def configure_for_performance(ds):
ds = ds.cache()
# ds = ds.shuffle(buffer_size=image_count)
ds = ds.batch(batch_size)
ds = ds.prefetch(buffer_size=AUTOTUNE)
return ds
train_ds = configure_for_performance(train_ds)
val_ds = configure_for_performance(val_ds)
return train_ds, val_ds
Can anyone please help me? Thanks!
Here is the rest of my code.
def initialize_model():
IMG_SIZE = (height, width)
preprocess_input = tf.keras.applications.vgg19.preprocess_input
IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.VGG19(input_shape=IMG_SHAPE,
include_top=False,
weights='imagenet')
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(class_num, activation=tf.nn.sigmoid, use_bias=True)
inputs = tf.keras.Input(shape=(height, width, 3))
x = preprocess_input(inputs)
x = base_model(x, training=True)
x = global_average_layer(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)
def custom_loss(y_gt, y_pred):
L1_loss_out = tf.math.abs(tf.math.subtract(y_gt, y_pred))
scaler = tf.pow(50.0, y_gt)
scaled_loss = tf.math.multiply(L1_loss_out, scaler)
scaled_loss = tf.math.reduce_mean(
scaled_loss, axis=None, keepdims=False, name=None
)
return scaled_loss
base_learning_rate = 0.001
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=base_learning_rate, momentum=0.9),
loss=custom_loss,
metrics=['mean_absolute_error']
)
return model
def train(data_index, epoch_num, save_path):
train_dataset, validation_dataset = get_dataset(data_index)
model = initialize_model()
model.summary()
history = model.fit(train_dataset,
epochs=epoch_num,
validation_data=validation_dataset)
model.save_weights(save_path)
return model, history

Problem about transfer value and combobox at wxPython

Hi I'm wxpython newbie.
and an week before I was upload my question and not yet solve.
so Today I need more help about my problem
so here is the code....
# -*- coding:utf-8 -*-
import wx
import sqlite3
from PIL import Image # for image processing
from wx.adv import Animation, AnimationCtrl # for gif Animation
conn = sqlite3.connect('reference_file.rre')
cur = conn.cursor()
class MyApp(wx.App):
def OnInit(self):
self.frame = errorCode_SAC(None, title ="Guide")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
class errorCode_SAC(wx.Frame):
# constructor
def __init__(self, parent, id=wx.ID_ANY, title="Search", pos=wx.DefaultPosition, size=(1500,650), style=wx.DEFAULT_FRAME_STYLE, name=""):
super(errorCode_SAC, self).__init__(parent, id, title, pos, size, style, name="")
self.Panel_err_sac = wx.Panel(self,wx.ID_ANY, pos=(0,0), size=(774, 608))
self.Panel_dd = wx.Panel(self, wx.ID_ANY, pos=(777,0), size=(1,608))
self.Panel_err_sac_result = wx.Panel(self,wx.ID_ANY, pos=(778,0), size=(706, 308))
self.Panel_err_image = wx.Panel(self,wx.ID_ANY, pos=(778,309), size=(706,300))
self.explBox_err_sac = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ Instruction ]", pos = (8,10), size=(756, 200))
self.lbname1 = wx.StaticText(self.explBox_err_sac, label="1.input name.",pos=(10,20))
self.sa_ra_code_box = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ input model ]", pos=(8,230), size=(340,80))
self.sa_err_code_CeNa = wx.TextCtrl(self.sa_ra_code_box, wx.ID_ANY, pos=(8,30), size=(260,22))
self.button = wx.Button(self.sa_ra_code_box, wx.ID_OK, label="search", size=(50,23), pos = (280,30))
self.button.SetDefault()
self.sa_er_Box = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ Search by input name ]", pos = (8,320), size = (340,280))
self.sa_er_inputkw = wx.StaticText(self.sa_er_Box, label="",pos=(8,15), size=(10,40), style=wx.ALIGN_LEFT)
self.sa_er_middle = wx.StaticText(self.sa_er_Box, label=" by", pos=(50,15))
self.sa_er_middle = wx.StaticText(self.sa_er_Box, label="", pos=(8,30))
self.sa_er_footer = wx.StaticText(self.sa_er_Box, label=" searched",pos=(50,30))
self.sa_er_svlist = wx.ListCtrl(self.sa_er_Box, -1, pos = (8,60), size = (330,200), style = wx.LC_REPORT | wx.SUNKEN_BORDER)
self.sa_er_svlist.InsertColumn(0,"model")
self.sa_er_svlist.InsertColumn(1,"spec")
self.sa_er_svlist.SetColumnWidth(0,100)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.sa_err_catelist_OnClick, self.sa_er_svlist)
self.button.Bind(wx.EVT_BUTTON, self.sa_err_search_OnButton)
self.sa_er_result_Box = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ check list ]", pos=(360,230), size =(405,370))
self.sa_er_question_ti = wx.StaticText(self.sa_er_result_Box, label="", pos=(50,20), size = (130,-1))
self.sa_er_question_text = wx.StaticText(self.sa_er_result_Box, label="point", pos = (10,50), size = (130,-1))
self.sa_er_question_te = wx.StaticText(self.sa_er_result_Box, label="", pos=(50,50), size = (130,-1))
self.P_err_sac_case1 = wx.StaticBox(self.Panel_err_sac_result, wx.ID_ANY, "[ check list below ]", pos = (8,10), size=(690,60))
self.P_err_sac_case2 = wx.StaticBox(self.Panel_err_sac_result, wx.ID_ANY, "[ symptom ]", pos=(8,90), size =(690,200))
self.cas2_symp = wx.StaticText(self.P_err_sac_case2, label="selected symptom is..", pos=(10,20))
self.cas2_symp_text = wx.StaticText(self.P_err_sac_case2, label="", pos=(10,40))
self.cas2_descrip = wx.StaticText(self.P_err_sac_case2, label="cause....", pos=(10,70))
self.cas2_descrip_text = wx.StaticText(self.P_err_sac_case2, label="", pos=(10,90))
# -- Combo box
items=[] # Dummy list
self.cb = wx.ComboBox(self.P_err_sac_case1, pos=(10,30),size=(500,20), choices=items, style=wx.CB_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.OnSelectComboBox)
# -- search query
def sa_err_search_OnButton(self, e):
self.sa_er_inputkw.SetLabel(self.sa_err_code_CeNa.GetValue())
searchResult = "%"+self.sa_err_code_CeNa.GetValue()+"%"
self.sa_er_svlist.DeleteAllItems()
sa_err_code_CeNa = cur.execute("Select * from sa_er_cate where cate like '"+searchResult+"'")
count = 0
for i in sa_err_code_CeNa:
self.sa_er_svlist.Append(i[1:3])
count = count +1
self.sa_er_middle.SetLabel(str(count))
self.Bind(wx.EVT_CLOSE, self.on_close)
def on_close(self,e):
self.Destroy()
def sa_err_catelist_OnClick(self, event):
sa_idx = event.GetIndex()
sa_err_check = self.sa_er_svlist.GetItem(sa_idx, 0).GetText()
sa_err_check_Comment = cur.execute("select cate,chek_comment from sa_er_cate where cate ='%s'" %sa_err_check)
for row in sa_err_check_Comment:
self.sa_er_question_ti.SetLabel(row[0])
self.sa_er_question_te.SetLabel(row[1])
model_name_string = row[0]
result_query_1 = cur.execute("Select symp from sac_er_ramp where cate='%s'" % model_name_string)
list=[]
for row_test in result_query_1:
list.append(row_test[0])
self.cb.SetItems(list)
def OnSelectComboBox(self,event):
item = event.GetString()
result_query_2 = cur.execute("Select symp, descrip, judgement,image from sac_er_ramp where symp='%s'" % item)
for row in result_query_2:
self.cas2_symp_text.SetLabel(row[0])
self.cas2_descrip_text.SetLabel(row[1])
imageno = row[3]
# -- IMAGE
erim = Image.open('./image/image_error_ramp/%s.webp' % imageno)
erim.info.pop('background',None)
erim.save('./image/image_error_ramp/%s.gif' % imageno,save_all=True, loop=0)
anim = Animation('./image/image_error_ramp/%s.gif' % imageno)
ctrl = AnimationCtrl(self.Panel_err_image, -1,anim, pos=(35,40))
ctrl.Play()
os.remove('./image/image_error_ramp/%s.gif' % imageno)
if __name__=="__main__":
app = MyApp(False)
app.MainLoop()
and progress of this code is below
input "model name" at textctrl
search "relate model" and button bind to event (to get a specific model name)
select a "model" from listctrl bind to event (to get a combobox's elements)
and combobox's list fill with relate list (list's element bring from sqlie)
select a combobox element and relate image is shown (image is animated GIF)
and below is my problem
when I select combobox list and Animated GIF is played at panel.
and select combobox's another element, Animated GIF play another and image is overlap
below code...image convert and play code... i call this code "IMAGE"
(I saved all Animated GIF to webp and convert to gif that time)
erim = Image.open('./image/image_error_ramp/%s.webp' % imageno)
erim.info.pop('background',None)
erim.save('./image/image_error_ramp/%s.gif' % imageno,save_all=True, loop=0)
anim = Animation('./image/image_error_ramp/%s.gif' % imageno)
ctrl = AnimationCtrl(self.Panel_err_image, -1,anim, pos=(35,40))
ctrl.Play()
os.remove('./image/image_error_ramp/%s.gif' % imageno)
So I think maybe Solve the problem to move "IMAGE" code locate below the constructor code(because init constructor is there.)
# constructor
def __init__(self, parent, id=wx.ID_ANY, title="Search", pos=wx.DefaultPosition, size=(1500,650), style=wx.DEFAULT_FRAME_STYLE, name=""):
IMAGE CODE
and here(below the constructor code) I can't get imageno (imageno is image's name. and this name bring from sqlite, so I select a element from a combobox but I can't get any response from combobox)
and my problem is this
Can I get the image's name from the sqlite at the below of constructor code with combobox?
or otherwise at original location(below the annotation "IMAGE") any code for "Animated GIF not overlapping" ?
ps. week a go robin dunn and rolf of saxony teach me about this problem
But I can't Understand and very depressed.....
Have a Niceday
It's quite difficult to know where to start with this answer, because there are coding errors, logical errors and I do not know what the data looks like.
However, several things stand out.
sqlite queries need a fetch to return the row/rows
use fetchone(), fetchmany(n) or fetchall()
When testing print() is your friend, if not using an IDE
print the result/s to check you have what you expect
Always assume that an error could have happened, test with if or try for example
Initialise variables, especially if you are setting them in an if statement
Assume the test could fail.
That said, I applaud your go for it attitude but you could have done this in smaller steps. Master each step before attempting to put them all together.
Here is a version of your code, that comes with many caveats.
I don't know your data or data structure.
I have started by creating some dummy records in my database.
I don't know your objectives or the logic.
Only those issues I needed to address to get a basically functioning program have been addressed and I've removed some code around the image processing to help me not you.
Hopefully, you can find some benefit in the code below.
I recommend using "diff" on my code versus yours, to see what has changed.
import wx
import sqlite3
from PIL import Image # for image processing
from wx.adv import Animation, AnimationCtrl # for gif Animation
conn = sqlite3.connect('reference_file.rre', isolation_level=None)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
result = cur.execute("create table if not exists sa_er_cate (cate TEXT PRIMARY KEY NOT NULL,chek_comment TEXT)");
result = cur.execute("create table if not exists sa_er_ramp (cate TEXT PRIMARY KEY NOT NULL, symp TEXT, descrip TEXT, judgement TEXT,image TEXT)");
# Define a default data
cur.execute("select * from sa_er_cate where (cate=?)",["no1"]);
MyCate = cur.fetchone()
if not MyCate:
try:
conn.execute("insert into sa_er_cate (cate, chek_comment) values (?,?)"\
,("no1","comment 1"));
except sqlite3.Error as e:
print('Default Cate Insert Error '+str(e), 'Error')
try:
conn.execute("insert into sa_er_cate (cate, chek_comment) values (?,?)"\
,("no2","comment 2"));
except sqlite3.Error as e:
print('Default Cate Insert Error '+str(e), 'Error')
cur.execute("select * from sa_er_ramp where (cate=?)",["no1"]);
MySymp = cur.fetchone()
if not MySymp:
try:
conn.execute("insert into sa_er_ramp (cate, symp, descrip, judgement, image) values (?,?,?,?,?)"\
,("no1","no1","description 1","judgement 1","Image1"));
except sqlite3.Error as e:
print('Default Symp Insert Error '+str(e), 'Error')
try:
conn.execute("insert into sa_er_ramp (cate,symp, descrip, judgement, image) values (?,?,?,?,?)"\
,("no2","no2","description 2","judgement 2","Image2"));
except sqlite3.Error as e:
print('Default Symp Insert Error '+str(e), 'Error')
class MyApp(wx.App):
def OnInit(self):
self.frame = errorCode_SAC(None, title ="Guide")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
class errorCode_SAC(wx.Frame):
# constructor
def __init__(self, parent, id=wx.ID_ANY, title="Search", pos=wx.DefaultPosition, size=(1500,650), style=wx.DEFAULT_FRAME_STYLE, name=""):
super(errorCode_SAC, self).__init__(parent, id, title, pos, size, style, name="")
self.Panel_err_sac = wx.Panel(self,wx.ID_ANY, pos=(0,0), size=(774, 608))
self.Panel_dd = wx.Panel(self, wx.ID_ANY, pos=(777,0), size=(1,608))
self.Panel_err_sac_result = wx.Panel(self,wx.ID_ANY, pos=(778,0), size=(706, 308))
self.Panel_err_image = wx.Panel(self,wx.ID_ANY, pos=(778,309), size=(706,300))
self.explBox_err_sac = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ Instruction ]", pos = (8,10), size=(756, 200))
self.lbname1 = wx.StaticText(self.explBox_err_sac, label="1.input name.",pos=(10,20))
self.sa_ra_code_box = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ input model ]", pos=(8,230), size=(340,80))
self.sa_err_code_CeNa = wx.TextCtrl(self.sa_ra_code_box, wx.ID_ANY, pos=(8,30), size=(260,22))
self.button = wx.Button(self.sa_ra_code_box, wx.ID_OK, label="search", size=(50,23), pos = (280,30))
self.button.SetDefault()
self.sa_er_Box = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ Search by input name ]", pos = (8,320), size = (340,280))
self.sa_er_inputkw = wx.StaticText(self.sa_er_Box, label="",pos=(8,15), size=(10,40), style=wx.ALIGN_LEFT)
self.sa_er_middle = wx.StaticText(self.sa_er_Box, label=" by", pos=(50,15))
self.sa_er_middle = wx.StaticText(self.sa_er_Box, label="", pos=(8,30))
self.sa_er_footer = wx.StaticText(self.sa_er_Box, label=" searched",pos=(50,30))
self.sa_er_svlist = wx.ListCtrl(self.sa_er_Box, -1, pos = (8,60), size = (330,200), style = wx.LC_REPORT | wx.SUNKEN_BORDER)
self.sa_er_svlist.InsertColumn(0,"model")
self.sa_er_svlist.InsertColumn(1,"spec")
self.sa_er_svlist.SetColumnWidth(0,100)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.sa_err_catelist_OnClick, self.sa_er_svlist)
self.button.Bind(wx.EVT_BUTTON, self.sa_err_search_OnButton)
self.sa_er_result_Box = wx.StaticBox(self.Panel_err_sac, wx.ID_ANY, "[ check list ]", pos=(360,230), size =(405,370))
self.sa_er_question_ti = wx.StaticText(self.sa_er_result_Box, label="", pos=(50,20), size = (130,-1))
self.sa_er_question_text = wx.StaticText(self.sa_er_result_Box, label="point", pos = (10,50), size = (130,-1))
self.sa_er_question_te = wx.StaticText(self.sa_er_result_Box, label="", pos=(50,50), size = (130,-1))
self.P_err_sac_case1 = wx.StaticBox(self.Panel_err_sac_result, wx.ID_ANY, "[ check list below ]", pos = (8,10), size=(690,80))
self.P_err_sac_case2 = wx.StaticBox(self.Panel_err_sac_result, wx.ID_ANY, "[ symptom ]", pos=(8,110), size =(690,200))
self.cas2_symp = wx.StaticText(self.P_err_sac_case2, label="selected symptom is..", pos=(10,20))
self.cas2_symp_text = wx.StaticText(self.P_err_sac_case2, label="", pos=(10,40))
self.cas2_descrip = wx.StaticText(self.P_err_sac_case2, label="cause....", pos=(10,70))
self.cas2_descrip_text = wx.StaticText(self.P_err_sac_case2, label="", pos=(10,90))
# -- Combo box
items=[] # Dummy list
self.cb = wx.ComboBox(self.P_err_sac_case1, pos=(10,30),size=(500,30), choices=items, style=wx.CB_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.OnSelectComboBox)
self.Bind(wx.EVT_CLOSE, self.on_close)
# -- search query
def sa_err_search_OnButton(self, e):
self.sa_er_inputkw.SetLabel(self.sa_err_code_CeNa.GetValue())
searchResult = "%"+self.sa_err_code_CeNa.GetValue()+"%"
self.sa_er_svlist.DeleteAllItems()
sa_err_code_CeNa = cur.execute("Select * from sa_er_cate where cate like '"+searchResult+"'")
rows = cur.fetchall()
count = 0
for i in rows:
self.sa_er_svlist.Append(i[0:3])
count += 1
self.sa_er_middle.SetLabel(str(count))
def on_close(self,e):
self.Destroy()
def sa_err_catelist_OnClick(self, event):
sa_idx = event.GetIndex()
sa_err_check = self.sa_er_svlist.GetItem(sa_idx, 0).GetText()
print("1",sa_err_check)
sa_err_check_Comment = cur.execute("select cate,chek_comment from sa_er_cate where cate ='%s'" %sa_err_check)
row = cur.fetchone()
print("2",row)
if row:
self.sa_er_question_ti.SetLabel(row[0])
self.sa_er_question_te.SetLabel(row[1])
print (row)
model_name_string = row[0]
result_query_1 = cur.execute("Select symp from sa_er_ramp where cate='%s'" % model_name_string)
rows = cur.fetchall()
res_list=["Select an option"]
for row_test in rows:
res_list.append(row_test[0])
self.cb.SetItems(res_list)
self.cb.SetSelection(0)
print(res_list)
self.Refresh()
def OnSelectComboBox(self,event):
item = event.GetString()
result_query_2 = cur.execute("Select symp, descrip, judgement,image from sa_er_ramp where symp='%s'" % item)
rows = cur.fetchall()
imageno = ""
for row in rows:
self.cas2_symp_text.SetLabel(row[0])
self.cas2_descrip_text.SetLabel(row[1])
imageno = row[3]
# -- IMAGE
print("Image selected:",imageno)
#erim = Image.open('./image/image_error_ramp/%s.webp' % imageno)
#erim.info.pop('background',None)
#erim.save('./image/image_error_ramp/%s.gif' % imageno,save_all=True, loop=0)
anim = Animation('./%s.gif' % imageno)
ctrl = AnimationCtrl(self.Panel_err_image, -1,anim, pos=(35,40))
ctrl.Play()
#os.remove('./image/image_error_ramp/%s.gif' % imageno)
if __name__=="__main__":
app = MyApp(False)
app.MainLoop()

decode TFRecord fail. Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\

I encoded some images to TFRecords as an example and then try to decode them. However, there is a bug during the decode process and I really cannot fix it.
InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\222\244\257\222\244\260\223\245\260\223\245\262\225\247\263'
[[{{node DecodeJpeg}}]] [Op:IteratorGetNextSync]
encode:
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _int64_feature(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
src_path = r"E:\data\example"
record_path = r"E:\data\data"
sum_per_file = 4
num = 0
key = 3
for img_name in os.listdir(src_path):
recordFileName = "trainPrecipitate.tfrecords"
writer = tf.io.TFRecordWriter(record_path + recordFileName)
img_path = os.path.join(src_path, img_name)
img = Image.open(img_path, "r")
height = np.array(img).shape[0]
width = np.array(img).shape[1]
img_raw = img.tobytes()
example = tf.train.Example(features = tf.train.Features(feature={
'image/encoded': _bytes_feature(img_raw),
'image/class/label': _int64_feature(key),
'image/height': _int64_feature(height),
'image/width': _int64_feature(width)
}))
writer.write(example.SerializeToString())
writer.close()
decode:
import IPython.display as display
train_files = tf.data.Dataset.list_files(r"E:\data\datatrainPrecipitate.tfrecords")
train_files = train_files.interleave(tf.data.TFRecordDataset)
def decode_example(example_proto):
image_feature_description = {
'image/height': tf.io.FixedLenFeature([], tf.int64),
'image/width': tf.io.FixedLenFeature([], tf.int64),
'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=3),
'image/encoded': tf.io.FixedLenFeature([], tf.string)
}
parsed_features = tf.io.parse_single_example(example_proto, image_feature_description)
height = tf.cast(parsed_features['image/height'], tf.int32)
width = tf.cast(parsed_features['image/width'], tf.int32)
label = tf.cast(parsed_features['image/class/label'], tf.int32)
image_buffer = parsed_features['image/encoded']
image = tf.io.decode_jpeg(image_buffer, channels=3)
image = tf.cast(image, tf.float32)
return image, label
def processed_dataset(dataset):
dataset = dataset.repeat()
dataset = dataset.batch(1)
dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
# print(dataset)
return dataset
train_dataset = train_files.map(decode_example)
# train_dataset = processed_dataset(train_dataset)
print(train_dataset)
for (image, label) in train_dataset:
print(repr(image))
InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\222\244\257\222\244\260\223\245\260\223\245\262\225\247\263'
[[{{node DecodeJpeg}}]] [Op:IteratorGetNextSync]
I can use tf.io.decode_raw() to decode the TFRecords and then use tf.reshape() to get the original image. While still don't know when to use tf.io.decode_raw() and when to use tf.io.decode_jpeg().

Python2.7 PNG Image into Button

I have been making a homepage for my games and I was trying to make a png image into a button. But I was incapable of doing so.
This is my code;
# Homepage Code
import sys
from Tkinter import *
button_flag = True
def click():
global button_flag
if button_flag:
button1.configure(bg='white')
button_flag = False
else:
button1.configure(bg='green')
button_flag = True
root = Tk()
mPage = Tk()
mPage.geometry('1000x1000')
mPage.title('Homepage')
mPage.configure(bg='#FFB6C1')
l = Label(mPage, text = 'Pick Which Game That You Want To Play?',font=('TW Cen MT',45), fg='white', bg='#FFB6C1')
l.pack()
hardest = Label(mPage, text = "World's Hardest Game",font=('Ariel',25), fg='white', bg='FFB6C1')
hardest.place(x=200, y=200)
hardestphoto = PhotoImage(file='HARD.PNG')
button1 = Button(mPage, width=155, height=55, image=hardestphoto, bg='#FFB6C1')
button1.place(x=200, y=350)
mPage.mainloop()
How would I be able to make my png image which is 'Hard.PNG' into a button?

wxpython, how to set background color and foreground color in textctrl?

I want to set color for words, background and foreground colors both are needed. I learned tkinter first, but it seems wxpython have no similar methods.
the following code is easy to test, copy "hello world, Hello World, heLLo WORLD" to area_example, tell me how to highlight "hello", ignorecase
#!/usr/bin/env python
# coding=utf8
import wx
rows = 5
cols = 2
vgap = 20
hgap = 10
class Search(wx.Frame):
#not_resizable = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX) # ok
not_resizable = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
def __init__(self, parent, title, size):
super(Search, self).__init__(parent, title=title, size=size, style=self.not_resizable)
self.init_elements()
self.lay_out()
self.Centre()
self.Show()
def init_elements(self):
self.panel = wx.Panel(self)
self.entry_name = wx.TextCtrl(self.panel)
self.entry_name.SetFocus()
self.btn_add = wx.Button(self.panel, label="Add")
self.btn_add.Disable()
self.btn_recite = wx.Button(self.panel, label="Recite")
self.btn_recite.Disable()
self.btn_flash = wx.Button(self.panel, label="Flash")
self.btn_flash.Disable()
self.label_phonetic = wx.StaticText(self.panel, label='')
self.area_meaning = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
self.area_example = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
self.btn_save = wx.Button(self.panel, label="Save")
self.btn_sort = wx.Button(self.panel, label="Sort")
def lay_out(self):
hbox = wx.BoxSizer(wx.HORIZONTAL)
grid = wx.FlexGridSizer(rows, cols, vgap, hgap)
grid.AddMany([
(self.entry_name), (self.btn_add),
(self.label_phonetic), (self.btn_recite),
(self.area_meaning, 1, wx.EXPAND), (self.btn_flash),
(self.area_example, 1, wx.EXPAND), (self.btn_sort),
(self.btn_save),
])
grid.AddGrowableCol(0, 1)
grid.AddGrowableRow(2, 1)
grid.AddGrowableRow(3, 1)
hbox.Add(grid, proportion=1, flag=wx.ALL | wx.EXPAND, border=15)
self.panel.SetSizer(hbox)
#self.panel.SetSizerAndFit(hbox)
def OnKeyUp(self, e):
code = e.GetKeyCode()
if code == wx.WXK_RETURN:
self.enter_handler(e)
def enter_handler(self, e):
word = self.entry_name.GetValue()
if word:
self.highlight(word)
def highlight(self, name):
# todo
# add background color and foreground color, ignore case
print 'highlight'
def search_test():
app = wx.App()
title = 'Search Test'
size = (800, 500)
s = Search(None, title, size)
s.entry_name.Bind(wx.EVT_KEY_UP, s.OnKeyUp)
app.MainLoop()
if __name__ == '__main__':
search_test()
the doc version when I asked the question was wxPython 3.0.3, last updated 13 March 2015 from revision 1725+2c3b7a8.
but the wxPython version brew install on osx was 3.0.2, some classes and methods were not available.
On the docs it explains how to do this: http://wxpython.org/Phoenix/docs/html/TextCtrl.html#phoenix-title-textctrl-styles
Here is an example snippet (Should go below your definition of self.area_example)
self.area_example.SetDefaultStyle(wx.TextAttr(wx.RED))
self.area_example.AppendText("Red text\n")
self.area_example.SetDefaultStyle(wx.TextAttr(wx.NullColour,
wx.LIGHT_GREY))
self.area_example.AppendText("Red on grey text\n")
self.area_example.SetDefaultStyle(wx.TextAttr(wx.BLUE))
self.area_example.AppendText("Blue on grey text\n")
As for checking if the word is "hello", I can only think right now as to bind it and check it.
self.area_example.Bind(wx.EVT_CHAR, self.OnKeyDown)
The "OnKeyDown" function is just an example. It runs but you'll most likely want a better way of doing it.
def OnKeyDown(self, e):
last_word = self.area_example.GetValue().split()[-1]
if last_word.lower() == "hello":
print("Change color")
e.Skip()
From there you should be able to accomplish what you need.

Resources