TensorFlow training gets slower every batch - performance

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

Related

Frame not appearing when it is supposed to... (ROBLOX GUI)

I am making an Os module that lets you create remote Operating systems but when the background frame loads in a new window just an random window loads in but it just basically gets "overwritten" by the background frame.
I have a post on scriptinghelpers: https://scriptinghelpers.org/questions/116285/instancenew-but-not-working-as-expected-module
but it seems that no one wants no one on the website knows how to do it
my code for the main Os module:
local module = {}
function module.__Version__()
local ROS = '1.00'
local ROS = tostring(ROS)
print('Version: '..ROS)
end
function module.create_environment(master)
local main = Instance.new('ScreenGui',master)
main.Name = ("ROS")
return(main)
end
function module.create_background(env)
local Frame = Instance.new('Frame',env)
Frame.Name = ('Background')
Frame.Size = UDim2.new(2,0,2,0)
Frame.Position = UDim2.new(0, 0,-0.5, 0)
Frame.BackgroundColor3 = Color3.new(0.337255, 0.290196, 1)
return(Frame)
end
function module.create_taskbar(env)
local main = Instance.new("Frame",env)
main.BackgroundColor3 = Color3.new(0, 0, 0)
main.Size = UDim2.new(2, 0,0, 45)
main.Position = UDim2.new(-0.5, 0,1, -45)
return(main)
end
function module.create_app_button(icon,env,X,Y)
local Btn = Instance.new('ImageButton',env)
Btn.Image = (tostring(icon))
Btn.Size = UDim2.new(0, 49,0, 49)
Btn.Position = UDim2.new(0, tonumber(X), 0, tonumber(Y))
return(Btn)
end
function module.create_clone_env(env)
local coloned_env = env:Clone()
coloned_env.Parent = env.Parent
end
function module.create_time_gui(env)
local main = Instance.new('TextLabel',env)
main.Size = UDim2.new(0, 115,0, 41)
main.Position = UDim2.new(1, -145,1, -44)
main.TextColor3 = Color3.new(1, 1, 1)
main.BackgroundTransparency = 1
main.TextScaled = true
main.Font = Enum.Font.Ubuntu
local assetId = 5990705305
local InsertService = game:GetService("InsertService")
local model = InsertService:LoadAsset(assetId)
model.Time_Manager.Parent = main
return(main)
end
function module.create_start_button(env)
local main_button = Instance.new('TextButton',env)
main_button.Size = UDim2.new(0, 146,0, 45)
main_button.Position = UDim2.new(0, 0,1, -44)
main_button.TextColor3 = Color3.new(0, 0, 0)
main_button.Text = "Start"
main_button.TextSize = 25
main_button.Font = Enum.Font.Arial
main_button.BorderSizePixel = 0
return(main_button)
end
function module.create_app(env)
local frame = Instance.new('Frame',env)
local round = Instance.new("UICorner",frame)
local top_frame = Instance.new('Frame',frame)
local exit_button = Instance.new('TextButton',top_frame)
local assetId = 5995055509
local InsertService = game:GetService("InsertService")
local model = InsertService:LoadAsset(assetId)
round.CornerRadius = UDim.new(0,20)
frame.Size = UDim2.new(0, 1084,0, 673)
frame.Position = UDim2.new(0.5, -542,0.5, -336)
frame.BackgroundColor3 = Color3.new(1, 1, 1)
top_frame.Size = UDim2.new(1, 0,0.003, 28)
top_frame.Position = UDim2.new(0, 0,0, 0)
top_frame.BackgroundColor3 = Color3.new(0.611765, 0.611765, 0.611765)
top_frame.BorderSizePixel = 0
exit_button.Size = UDim2.new(0, 74,0, 30)
exit_button.Position = UDim2.new(1, -74,0.5, -15)
exit_button.Text = ("X")
exit_button.BorderSizePixel = 0
exit_button.TextColor3 = Color3.new(1, 1, 1)
exit_button.BackgroundColor3 = Color3.new(1, 0, 0)
exit_button.TextStrokeTransparency = 0
exit_button.TextSize = 17
model.LocalScript.Parent = exit_button
model:Destroy()
return(frame)
end
return module
Everything works; create_taskbar(),create_time_gui(),create_start_button()
But its just the create_app()
This is what my Os-module made:
This is the OS my Os-module made:
As i said the background overwrites my create_app() is there a way to prevent this?
If maintaining the element hierarchy is important, try adjusting the ZIndex of the background frame and the app so that the two aren't fighting for which one appears on top. Elements with smaller numbers for their ZIndex will render first, meaning they will appear behind elements with larger ones.
function module.create_background(env)
local Frame = Instance.new('Frame',env)
Frame.ZIndex = 1
-- <a bunch of other code>
return Frame
end
And then make the app's ZIndex higher.
function module.create_app(env)
local frame = Instance.new('Frame', env)
frame.ZIndex = 2
-- <a bunch of other code>
return frame
end
But you should be careful. Messing with ZIndices can get really messy really quick. A better alternative would be to just set the app Frame's parent to the background Frame.

callback via taptool presents datatable

From what I can tell in my limited review of bokeh documentation the ability to click on a glyph on a plot then present a Dialog box or Datatable is a feature not yet available. I do not want the Datatable to be presented until a glyph has been selected. Would ideally like the ability to hide the Dialog or Datatable as well.
It seems that bokeh.models.widgets.dialog were deprecated sometime after 0.10.0. I could use that but its not available in python 3.7 at this point. Suggestions?
Some features are not officially supported but sometimes one can come up with a work-arounds like this one (tested on Bokeh v1.0.4):
from bokeh.plotting import figure, show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider, DataTable, TableColumn, CustomJS
plot = figure(tools = 'tap')
source = ColumnDataSource(dict(x = list(range(6)), y = [x ** 2 for x in range(6)]))
circles = plot.circle('x', 'y', source = source, size = 20)
slider = Slider(start = -1, end = 5, value = 6, step = 1, title = "i", width = 300)
columns = [TableColumn(field = "x", title = "x"), TableColumn(field = "y", title = "x**2")]
table = DataTable(source = source, columns = columns, width = 320)
plot.js_on_event('tap', CustomJS(args = {'table': table, 'source': source, 'slider': slider}, code = '''
const selected_index = source.selected.indices[0]
if (selected_index != null)
table.height = 0;
else
table.height = slider.value * 25 + 25;'''))
callback_code = """ i = slider.value;
new_data = {"x": [0,1,2,3,4,5], "y": [0,1,4,9,16,25]}
table.source.data = new_data
table.height = i * 25 + 25; """
callback = CustomJS(args = dict(slider = slider, table = table), code = callback_code)
slider.js_on_change('value', callback)
show(column(slider, plot, table))
Result:

I m new to Matlab and currently working of weapon detection in images but i m getting false positives here.What should i do?

How can i caluclate the F1 score using matlab .This code is giving positive results in negative samples also .I think thats because of dynamic background of images in datset. Should i change the dataset for better accuracy or change the approach .Please Help
Thanks
DataSet : http://kt.agh.edu.pl/~matiolanski/KnivesImagesDatabase/KnivesImagesDatabase.rar
CODE:`
TrainingSet = imageSet('Trainingset','recursive');
testSet= imageSet('TestSet','recursive');
img=read(TrainingSet(1),1);
[hog_4x4, vis4x4] = extractHOGFeatures(img,'CellSize',[4 4]);
cellSize = [4 4];
hogFeatureSize = length(hog_4x4);
trainingFeatures= [];
trainingLabels = [];
x= TrainingSet(1).Count;
y= TrainingSet(2).Count;
for digit = 1:numel(TrainingSet)-1
numImages = TrainingSet(digit).Count;
for i = 1:numImages-1
img = rgb2gray(read(TrainingSet(digit), i));
%Apply pre-processing steps
features(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);
end
%labels = repmat(TrainingSet(digit).Description, numImages, 1);
trainingFeatures = [trainingFeatures; features];
%trainingLabels = [trainingLabels; labels ];
end
negativeSize = size(trainingFeatures,1);
trainingLabels = zeros(size(trainingFeatures,1),1);
for digit = 2:2
numImages= TrainingSet(digit).Count;
for i = 1:numImages-1
img = rgb2gray(read(TrainingSet(digit), (i)));
features1(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);
end
%labels = repmat(TrainingSet(digit).Description, numImages, 1);
trainingFeatures = [trainingFeatures; features1];
%trainingLabels = [trainingLabels; labels ];
end
positiveLabels = ones(size(trainingFeatures,1) - negativeSize,1);
trainingLabels = [trainingLabels ; positiveLabels];
classifier = fitcsvm(trainingFeatures, trainingLabels);
classOrder =classifier.ClassNames;
img=read(testSet(1),1);
img = rgb2gray(img);
[testFeatures, testLabels] = extractHOGFeatures(img, 'CellSize', cellSize);
%Make class predictions using the test features.
predictedLabels = predict(classifier, testFeatures);
if(predictedLabels==1)
warndlg('Object Detected','!! Warning !!');
else
warndlg('Object Not Detected','!! Warning !!');
end
I strongly recommend using Faster-rcnn for the problem. It is one of the state-of-the art Convolutional Neural Network architectures used extensively for object detection task. Here is a matlab implementation of the same.

AS3 SharedObject - Background images fails to load correctly. Set of images stored inside MC fails to load correct image from save

having issues with making a set of background images save and load correctly. Please note, that this has worked correctly in the past with "1 - 2" images in the caseSwapper.
Structure :
On my stage I have set of draggable objects that you can save and load as you please. (these work)
The background, which is movieClip called "caseSwapper" contains a set of frames with different images inside each frame. E.G frame one is called (labelled) "frameone" - contains a pretty picture. Frame 2 is labelled "Frametwo" which contains an alternative image etc etc
A load and save button on the stage allows you to store the data to sharedObject "mySO"
Issues and Behaviour
On the face of it, the save appears to be working. The trace statement is declaring that the current frame is being stored to mySO... although I'm not entirely convinced it is. Basically, when the player has a certain background selected and they click 'save' I need the current image to be saved/written to the sharedObject.
Notes : Frame 1 appears to work when I click 'load' from the stage. When I 'launch' the application (not load) even after saving frame 123 or 4 only frame 4 launches/dis[lays. I then have to click load to retrieve my sharedObject... which only shows the first frame... Any pointers. Script to edit is at the bottom. Please Note, that I'm designer first and foremost!
save_btn.addEventListener (MouseEvent.CLICK, clickersave);
function clickersave (e:MouseEvent):void {
saved.play();
mySO.data.myblcskull_mc_x = blcskull_mc.x;
mySO.data.myblcskull_mc_y = blcskull_mc.y;
mySO.data.myblackhandbag_mc_y = blackhandbag_mc.y;
mySO.data.myblackhandbag_mc_x = blackhandbag_mc.x;
mySO.data.myhotlips_mc_x = hotlips_mc.x;
mySO.data.myhotlips_mc_y = hotlips_mc.y;
mySO.data.my_x = bones_mc.x;
mySO.data.my_y = bones_mc.y;
mySO.data.mybut_x = btrfly_mc.x;
mySO.data.mybut_y = btrfly_mc.y;
mySO.data.mytig_x = tiger_mc.x;
mySO.data.mytig_y = tiger_mc.y;
mySO.data.myskullface_mc_y = skullface_mc.y;
mySO.data.myskullface_mc_x = skullface_mc.x;
mySO.data.myblack_tile_mc_zero_y = black_tile_mc_zero.y;
mySO.data.myblack_tile_mc_zero_x = black_tile_mc_zero.x;
mySO.data.myblack_tile_mc_one_x = black_tile_mc_one.x;
mySO.data.myblack_tile_mc_one_y = black_tile_mc_one.y;
mySO.data.mycrown_mc_y = crown_mc.y;
mySO.data.mycrown_mc_x = crown_mc.x;
mySO.data.myperfume_mc_y = perfume_mc.y;
mySO.data.myperfume_mc_x = perfume_mc.x;
mySO.data.myheart_mc_x = heart_mc.x;
mySO.data.myheart_mc_y = heart_mc.y;
mySO.data.myrose_mc_y = rose_mc.y;
mySO.data.myrose_mc_x = rose_mc.x;
// tears saved - - - - - - -
mySO.data.mytear_drop_mc_one_x = tear_drop_mc_one.x;
mySO.data.mytear_drop_mc_one_y = tear_drop_mc_one.y;
mySO.data.mytearup_drop_mc_three_x = tearup_drop_mc_three.x;
mySO.data.mytearup_drop_mc_three_y = tearup_drop_mc_three.y;
mySO.data.mytearup_drop_mc_four_x = tearup_drop_mc_four.x;
mySO.data.mytearup_drop_mc_four_y = tearup_drop_mc_four.y;
mySO.data.mytear_drop_mc_two_x = tear_drop_mc.x;
mySO.data.mytear_drop_mc_two_y = tear_drop_mc.y;
mySO.data.mytear_side_mc_one_x = tear_side_mc_one.x;
mySO.data.mytear_side_mc_one_y = tear_side_mc_one.y;
mySO.data.mytear_side_mc_two_x = tear_side_mc_two.x;
mySO.data.mytear_side_mc_two_y = tear_side_mc_two.y;
mySO.data.mytear_op_mc_one_y = tear_op_mc_one.y;
mySO.data.mytear_op_mc_one_x = tear_op_mc_one.x;
mySO.data.mytear_op_mc_two_y = tear_op_mc_two.y;
mySO.data.mytear_op_mc_two_x = tear_op_mc_two.x;
//tear_op_mc_one
// pink gems
mySO.data.mypink_jewel_mc_one_x = pink_jewel_mc_one.x;
mySO.data.mypink_jewel_mc_one_y = pink_jewel_mc_one.y;
mySO.data.mypink_jewel_mc_two_x = pink_jewel_mc_two.x;
mySO.data.mypink_jewel_mc_two_y = pink_jewel_mc_two.y;
mySO.data.mypink_jewel_mc_three_x = pink_jewel_mc_three.x;
mySO.data.mypink_jewel_mc_three_y = pink_jewel_mc_three.y;
mySO.data.mypink_jewel_mc_four_x = pink_jewel_mc_four.x;
mySO.data.mypink_jewel_mc_four_y = pink_jewel_mc_four.y;
mySO.data.mypink_jewel_mc_five_x = pink_jewel_mc_five.x;
mySO.data.mypink_jewel_mc_five_y = pink_jewel_mc_five.y;
mySO.data.mypink_jewel_mc_six_x = pink_jewel_mc_six.x;
mySO.data.mypink_jewel_mc_six_y = pink_jewel_mc_six.y;
mySO.data.mypink_jewel_mc_seven_x = pink_jewel_mc_seven.x;
mySO.data.mypink_jewel_mc_seven_y = pink_jewel_mc_seven.y;
mySO.data.mypink_jewel_mc_eight_x = pink_jewel_mc_eight.x;
mySO.data.mypink_jewel_mc_eight_y = pink_jewel_mc_eight.y;
mySO.data.mypink_jewel_mc_nine_x = pink_jewel_mc_nine.x;
mySO.data.mypink_jewel_mc_nine_y = pink_jewel_mc_nine.y;
// bg saves
mySO.data.myBgFrame = 1;
mySO.data.myBgFrameone = 2;
mySO.data.myBgFrametwo = 3;
mySO.data.myBgFramethree = 4;
trace("bgbackgrounds");
// silver gems - - - - - - - - -
mySO.data.mycircle_gem_mc_x = circle_gem_mc.x;
mySO.data.mycircle_gem_mc_y = circle_gem_mc.y;
mySO.data.mycircle_gem_mc_two_x = circle_gem_mc_two.x;
mySO.data.mycircle_gem_mc_two_y = circle_gem_mc_two.y;
mySO.data.mycircle_gem_mc_thirteen_x = circle_gem_mc_thirteen.x;
mySO.data.mycircle_gem_mc_thirteen_y = circle_gem_mc_thirteen.y;
//circle_gem_mc_six
mySO.flush ();
}
if (mySO.data.myBgFrame){
caseSwapper.gotoAndStop(mySO.data.myBgFrame);
}
if (mySO.data.myBgFrameone){
caseSwapper.gotoAndStop(mySO.data.myBgFrameone);
}
if (mySO.data.myBgFrametwo){
caseSwapper.gotoAndStop(mySO.data.myBgFrametwo);
}
if (mySO.data.myBgFramethree){
caseSwapper.gotoAndStop(mySO.data.myBgFramethree);
}
//caseSwapper.currentFrame = mySO.data.myBgFrame;
/////// ---------------------- loader
// ---------------------- LOADER -------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// when load button is clicked it loads the x and y position of dragged objects pulled from the
//sharedOject, it remembers the last var!
load_btn.addEventListener (MouseEvent.CLICK, loadlast);
function loadlast (e:MouseEvent):void {
//saved.play();
caseSwapper.gotoAndStop(mySO.data.myBgFrame);
//caseSwapper.currentFrame = mySO.data.myBgFrame;
//caseSwapper.gotoAndStop(mySO.data.myBgFrameone);
//caseSwapper.gotoAndStop(mySO.data.myBgFrametwo);
//caseSwapper.gotoAndStop(mySO.data.myBgFramethree);
//caseSwapper.gotoAndStop(mySO.data.myBgFramefour);
blcskull_mc.x = mySO.data.myblcskull_mc_x;
blcskull_mc.y = mySO.data.myblcskull_mc_y;
blackhandbag_mc.y = mySO.data.myblackhandbag_mc_y;
blackhandbag_mc.x = mySO.data.myblackhandbag_mc_x;
bones_mc.x = mySO.data.my_x;
bones_mc.y = mySO.data.my_y;
tiger_mc.x = mySO.data.mytig_x;
tiger_mc.y = mySO.data.mytig_y;
btrfly_mc.x = mySO.data.mybut_x;
btrfly_mc.y = mySO.data.mybut_y;
crown_mc.x = mySO.data.mycrown_mc_x;
crown_mc.y = mySO.data.mycrown_mc_y;
perfume_mc.x = mySO.data.myperfume_mc_x;
perfume_mc.y = mySO.data.myperfume_mc_y;
heart_mc.x = mySO.data.myheart_mc_x;
heart_mc.y = mySO.data.myheart_mc_y;
rose_mc.y = mySO.data.myrose_mc_y;
rose_mc.x = mySO.data.myrose_mc_x;
pink_jewel_mc_one.x = mySO.data.mypink_jewel_mc_one_x;
pink_jewel_mc_one.y = mySO.data.mypink_jewel_mc_one_y;
pink_jewel_mc_two.x = mySO.data.mypink_jewel_mc_two_x;
pink_jewel_mc_two.y = mySO.data.mypink_jewel_mc_two_y;
pink_jewel_mc_three.x = mySO.data.mypink_jewel_mc_three_x;
pink_jewel_mc_three.y = mySO.data.mypink_jewel_mc_three_y;
pink_jewel_mc_four.x = mySO.data.mypink_jewel_mc_four_x;
pink_jewel_mc_four.y = mySO.data.mypink_jewel_mc_four_y;
pink_jewel_mc_five.x = mySO.data.mypink_jewel_mc_five_x;
pink_jewel_mc_five.y = mySO.data.mypink_jewel_mc_five_y;
pink_jewel_mc_six.x = mySO.data.mypink_jewel_mc_six_x;
pink_jewel_mc_six.y = mySO.data.mypink_jewel_mc_six_y;
pink_jewel_mc_seven.x = mySO.data.mypink_jewel_mc_seven_x;
pink_jewel_mc_seven.y = mySO.data.mypink_jewel_mc_seven_y;
pink_jewel_mc_eight.x = mySO.data.mypink_jewel_mc_eight_x;
pink_jewel_mc_eight.y = mySO.data.mypink_jewel_mc_eight_y;
pink_jewel_mc_nine.x = mySO.data.mypink_jewel_mc_nine_x;
pink_jewel_mc_nine.y = mySO.data.mypink_jewel_mc_nine_y;
hotlips_mc.x = mySO.data.myhotlips_mc_x;
hotlips_mc.y = mySO.data.myhotlips_mc_y;
tearup_drop_mc_three.y = mySO.data.mytearup_drop_mc_three_y;
tearup_drop_mc_three.x = mySO.data.mytearup_drop_mc_three_x;
tearup_drop_mc_four.x = mySO.data.mytearup_drop_mc_four_x;
tearup_drop_mc_four.y = mySO.data.mytearup_drop_mc_four_y;
tear_side_mc_one.x = mySO.data.mytear_side_mc_one_x;
tear_side_mc_one.y = mySO.data.mytear_side_mc_one_y;
//tear_side_mc_two.x = mySO.data.mytear_side_mc_two_x;
//tear_side_mc_two.y = mySO.data.mytear_side_mc_two_y;
tear_op_mc_one.y = mySO.data.mytear_op_mc_one_y;
tear_op_mc_one.x = mySO.data.mytear_op_mc_one_x;
tear_op_mc_two.y = mySO.data.mytear_op_mc_two_y;
tear_op_mc_two.x = mySO.data.mytear_op_mc_two_x;
//--- silver little gems -----------------
circle_gem_mc_thirteen.x = mySO.data.mycircle_gem_mc_thirteen_x;
circle_gem_mc_thirteen.y = mySO.data.mycircle_gem_mc_thirteen_y;
circle_gem_mc_two.x = mySO.data.mycircle_circle_gem_mc_two_x;
circle_gem_mc_two.y = mySO.data.mycircle_circle_gem_mc_two_y;
mySO.flush ();
}
You're not actually storing the current frame anywhere — this section just saves the same numbers every time:
mySO.data.myBgFrame = 1;
mySO.data.myBgFrameone = 2;
mySO.data.myBgFrametwo = 3;
mySO.data.myBgFramethree = 4;
This is also why you're only seeing frame four when you launch, because all of your if statements see a positive number (and anything other than zero or NaN counts as true), so they all get executed one after the other.
Instead of the above, all you need is this in your save function:
mySO.data.myBgFrame = caseSwapper.currentFrame;
Then if you want to jump to that frame on launch, you only need your first if statement:
if (mySO.data.myBgFrame){
caseSwapper.gotoAndStop(mySO.data.myBgFrame);
}

3d animation from cinema4d to blender

I need to import a mesh animation from Cinema4D into Blender.
I tried to do that using Collada.The Collada 1.3 importer doesn't seem to
do anything, the Collada 1.4 importer seems to work, but the animation didn't get
imported into Blender.
After reading this post:
Problem solved!
In case anyone comes in here looking
for the answer, I spoke to Otomo via
email and he kindly explained that the
problem lies in the .dae file being
exported incorrectly from C4D.
I hope Otomo doesn't mind me quoting
his email, I just don't want other
people to waste the time I did on such
a stupid problem.
Open up the .dae in a text editor and
change:
data
data
to this:
data
data
The fps must also be the same in both
c4d and blender.
I tried that, but I get an error:
FEEDBACK: Illusoft Collada 1.4 Plugin v0.3.162 started
The minor version of the file you are using is newer then the plug-in, so errors may occur.
image not found: None
Traceback (most recent call last):
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/cstartup.py", line 681, in ButtonEvent
onlyMainScene, applyModifiers)
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/translator.py", line 120, in __init__
self.__Import(fileName)
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/translator.py", line 127, in __Import
documentTranslator.Import(fileName)
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/translator.py", line 333, in Import
self.sceneGraph.LoadFromCollada(self.colladaDocument.visualScenesLibrary.items, self.colladaDocument.scene)
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/translator.py", line 550, in LoadFromCollada
ob = sceneNode.ObjectFromDae(daeNode)
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/translator.py", line 2079, in ObjectFromDae
a.LoadFromDae(daeAnimation, daeNode, newObject)
File "/Applications/blender/blender.app/Contents/MacOS/.blender/scripts/bpymodules/colladaImEx/translator.py", line 1254, in LoadFromDae
interpolationsSource = daeAnimation.GetSource(interpolations.source)
AttributeError: 'NoneType' object has no attribute 'source'
Has anyone come across this issue ? Where can I find a newer Collada importer ?
Any hints on modifying the importer ?
Note:
Blender 2.5a2 imports collada animations, but the coordinate system is different and not all animation makes it through. For example, when I animate a box from 0,0,0 to 100,100,100,
rotate it on x,y,z and scale it on x,y,z, in Blender I get: translation on 1 axis(x which originally is y in cinema 4d), rotation is fine, scale is ignored.
I ended up writing a script.
I barely found usable C.O.F.F.E.E. documentation so went ahead and installed py4D.
The documentation is pretty good and the support on the forum is amazing.
Here's the current script:
import c4d
from c4d import documents,UVWTag
from c4d.utils import Deg
from c4d import symbols as sy, plugins, utils, bitmaps, gui
import math
def BlenderExport():
if not op: return
if op.GetType() != 5100:
print 'Selected Object is not an editable mesh'
return
unit = 0.001#for scale
foffset = 1#for frames
bd = doc.GetRenderBaseDraw()
scr = bd.GetFrameScreen()
rd = doc.GetActiveRenderData()
sizeX = int(rd[sy.RDATA_XRES_VIRTUAL])
sizeY = int(rd[sy.RDATA_YRES_VIRTUAL])
name = op.GetName()
fps = doc.GetFps()
sFrame= doc.GetMinTime().GetFrame(fps)
eFrame= doc.GetMaxTime().GetFrame(fps)
code = 'import Blender\nfrom Blender import *\nimport bpy\nfrom Blender.Mathutils import *\n\nscn = bpy.data.scenes.active\ncontext=scn.getRenderingContext()\ncontext.fps = '+str(fps)+'\ncontext.sFrame = '+str(sFrame)+'\ncontext.eFrame = '+str(eFrame)+'\ncontext.sizeX = '+str(sizeX)+'\ncontext.sizeY = ' + str(sizeY) + '\n'
def GetMesh(code):
# goto 0
doc.SetTime(c4d.BaseTime(0, fps))
c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
doc.SetTime(doc.GetTime())
c4d.EventAdd(c4d.EVENT_ANIMATE)
code += 'editmode = Window.EditMode()\nif editmode:\tWindow.EditMode(0)\n'
coords4D = op.GetPointAll()
coords = 'coords = ['
uvw = 0
uvs = 'uvs = ['
for tag in op.GetTags():
if tag.GetName() == "UVW":
uvw = tag
for c in coords4D:
coords += '['+str(c.x*unit)+','+str(c.z*unit)+','+str(c.y*unit)+'],'
coords = coords.rpartition(',')[0] + ']\n'
faces4D = op.GetAllPolygons()
fcount = 0
faces = 'faces = ['
for f in faces4D:
faces += '['+str(f)+'],'
uv = uvw.Get(fcount);
uvs += '[Vector('+str(uv[0].x)+','+str(1.0-uv[0].y)+'),Vector('+str(uv[1].x)+','+str(1.0-uv[1].y)+'),Vector('+str(uv[2].x)+','+str(1.0-uv[2].y)+')],'
fcount += 1
faces = faces.rpartition(',')[0] + ']\n'
uvs = uvs.rpartition(',')[0] + ']\n'
code = code + coords + faces + uvs
code += "c4dmesh = bpy.data.meshes.new('"+name+"_mesh')\nc4dmesh.verts.extend(coords)\nc4dmesh.faces.extend(faces)\n\nob = scn.objects.new(c4dmesh,'"+name+"_obj')\nc4dmesh.flipNormals()\n\nif editmode:\tWindow.EditMode(1)\n\n"
code += "c4dmesh.quadToTriangle()\nc4dmesh.addUVLayer('c4duv')\n"
code += "for f in range(0,"+str(fcount)+"):\n\tc4dmesh.faces[f].uv = uvs[f]\n"
return code
def GetIPOKeys(code):
# store properties for tracks
tracks = op.GetCTracks()
# 0,1,2 = Position, 3,4,5 = Scale, 6,7,8 = Rotation, 9 = PLA
# props = [[lx,f],[ly,f],[lz,f],[sx,f],[sy,f],[sz,f],[rx,f],[ry,f],[rz,f]]
try:
props = []
trackIDs = [3,4,5,6,7,8,0,2,1]
propVals = ['LocX','LocZ','LocY','SizeX','SizeY','SizeZ','RotZ','RotX','RotY']
propIPOs = ['Ipo.OB_LOCX','Ipo.OB_LOCZ','Ipo.OB_LOCY','Ipo.OB_SCALEX','Ipo.OB_SCALEY','Ipo.OB_SCALEY','Ipo.OB_ROTZ','Ipo.OB_ROTX','Ipo.OB_ROTY']
for t in range(0,9):
props.append([[],[]])
curve = tracks[t].GetCurve()
keyCount = curve.GetKeyCount()
for k in range(0,keyCount):
key = curve.GetKey(k)
props[t][0].append(key.GetValue())
props[t][1].append(key.GetTime().GetFrame(fps))
# find the max key
maxProp = max(enumerate(props), key = lambda tup: len(tup[1]))[1][1]
maxKeys = len(maxProp)
# loop through tracks and keys
for key in range(0,maxKeys):
code += "Blender.Set('curframe',"+str(maxProp[key])+")\n"
for track in trackIDs:
if(key < len(props[track][0])):
code += "ob."+propVals[track] + " = " + str(props[track][0][key]) + '\n'
code += 'key = ob.insertIpoKey(' + propIPOs[track] + ')\n'
except:
pass
return code
# mesh/morph animation -> mesh always has the same number of verts
def GetShapeKeys(code):
track = 0;
tracks = op.GetCTracks()
for t in tracks:
if(t.GetName() == 'PLA'): track = t
# track = op.GetCTracks()[9]
if track != 0:
curve = track.GetCurve()
keyCount = curve.GetKeyCount()
verts = []
frames = []
vertsNum = op.GetPointCount()
ctime = doc.GetTime()
for k in range(1,keyCount):
key = curve.GetKey(k)
frames.append(key.GetTime().GetFrame(fps))
c4d.StatusSetBar(100*(k/keyCount))
doc.SetTime(key.GetTime())
c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
c4dvecs = op.GetPointAll();
blendvecs = []
for v in c4dvecs:
blendvecs.append([v.x*unit,v.z*unit,v.y*unit])
verts.append(blendvecs)
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
doc.SetTime(ctime)
c4d.EventAdd(c4d.EVENT_ANIMATE)
c4d.StatusClear()
code += '\n\n# shape keys\nverts = ' + str(verts) + '\n'
code += "if(ob.activeShape == 0):\n\tob.insertShapeKey()\n\n"
for f in range(0,len(frames)):
kNum = str(f+1)
code += "if editmode: Window.EditMode(0)\n"
code += "for v in range(0,"+str(vertsNum)+"):\n\tc4dmesh.verts[v].co.x = verts["+str(f)+"][v][0]\n\tc4dmesh.verts[v].co.y = verts["+str(f)+"][v][1]\n\tc4dmesh.verts[v].co.z = verts["+str(f)+"][v][2]\n"
code += "c4dmesh.calcNormals()\n"
code += "ob.insertShapeKey()\n"
code += "if editmode: Window.EditMode(1)\n"
code += "shapeKey = ob.getData().getKey()\n"
code += "newIpo = Ipo.New('Key','newIpo')\n"
code += "if(shapeKey.ipo == None): shapeKey.ipo = newIpo\n"
code += "if(shapeKey.ipo['Key "+kNum+"'] == None): shapeKey.ipo.addCurve('Key "+kNum+"')\n"
if(f == 0): code += "shapeKey.ipo['Key "+kNum+"'].append(BezTriple.New(1.0,0.0,0.0))\n"
if(f > 0): code += "shapeKey.ipo['Key "+kNum+"'].append(BezTriple.New("+str(float(frames[f-1]))+",0.0,0.0))\n"
code += "shapeKey.ipo['Key "+kNum+"'].append(BezTriple.New("+str(float(frames[f]))+",1.0,0.0))\n"
else:
#no PLA tracks, look for morph tag
vertsNum = op.GetPointCount()
for tag in op.GetTags():
if tag.GetType() == 1019633:
# print tag[sy.MORPHTAG_MORPHS]
'''
work around
1. store first key for each track curve
2. set the first key value to 1 for the 1st track and 0 for the others
3. store the mesh vertices -> track name verts = []
4. after all track verts are stored, restore the original values
5. write the the curve keys for blender shape keys
'''
code += "if(ob.activeShape == 0):\n\tob.insertShapeKey()\n\n"
tc = 0
tcs = str(tc+1)
for track in tag.GetCTracks():
curve = track.GetCurve()
value = curve.GetKey(0).GetValue()
curve.GetKey(0).SetValue(curve,1.0)
print track.GetName()
doc.SetTime(c4d.BaseTime(0, fps))
c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
c4dvecs = op.GetPointAll();
blendverts = []
for v in c4dvecs:
blendverts.append([v.x*unit,v.z*unit,v.y*unit])
code += "Key"+tcs+"verts = " + str(blendverts)+"\n"
code += "if editmode: Window.EditMode(0)\n"
code += "for v in range(0,"+str(vertsNum)+"):\n\tc4dmesh.verts[v].co.x = Key"+tcs+"verts[v][0]\n\tc4dmesh.verts[v].co.y = Key"+tcs+"verts[v][1]\n\tc4dmesh.verts[v].co.z = Key"+tcs+"verts[v][2]\n"
code += "c4dmesh.calcNormals()\n"
code += "ob.insertShapeKey()\n"
code += "if editmode: Window.EditMode(1)\n"
code += "shapeKey = ob.getData().getKey()\n"
code += "newIpo = Ipo.New('Key','newIpo')\n"
code += "if(shapeKey.ipo == None): shapeKey.ipo = newIpo\n"
code += "if(shapeKey.ipo['Key "+tcs+"'] == None): shapeKey.ipo.addCurve('Key "+tcs+"')\n"
print op.GetPointAll()
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
curve.GetKey(0).SetValue(curve,value)
keyCount = curve.GetKeyCount()
for k in range(0,keyCount):
key = curve.GetKey(k)
value = key.GetValue()
frame = key.GetTime().GetFrame(fps)
code += "shapeKey.ipo['Key "+tcs+"'].append(BezTriple.New("+str(float(frame))+","+str(value)+",0.0))\n"
tc += 1
tcs = str(tc+1)
c4d.EventAdd(c4d.EVENT_ANIMATE)
return code
def GetCamera(code):
bd = doc.GetRenderBaseDraw()
cp = bd.GetSceneCamera(doc)
if cp is None: cp = bd.GetEditorCamera()
fov = Deg(cp[sy.CAMERAOBJECT_FOV])
pos = cp.GetPos()
rot = cp.GetRot()
code += "\nc4dCam = Camera.New('persp','c4d_"+cp.GetName()+"')\nc4dCam.drawPassepartout = True\nc4dCam.alpha = 0.5\nc4dCam.drawLimits = 1\nc4dCam.dofDist = 100.0\n"
code += "c4dCam.angle = "+str(fov)+"\nc4dCamLens = c4dCam.lens\nc4dCam.lens = c4dCamLens\nWindow.RedrawAll()\nc4dCamObj = scn.objects.new(c4dCam)\n"
code += "c4dCamObj.setLocation("+str([pos.x,pos.z,pos.y])+")\n"
code += "c4dCamObj.setEuler("+str([rot.x+(math.pi*.5),rot.y,rot.z])+")\n"
code += "scn.setCurrentCamera(c4dCamObj)\n"
return code
code = GetMesh(code)
code = GetIPOKeys(code)
code = GetShapeKeys(code)
code = GetCamera(code)
file = open(doc.GetDocumentPath()+'/'+op.GetName()+'_export.py','w')
file.write(code)
file.close()
BlenderExport()
It supports ipo keys(position,rotation,scale).
Point Level Animation gets converted to multiple shape keys.
Morph Tag animation preserves nicely.

Resources