OpenShot Library | libopenshot 1.1.1
Loading...
Searching...
No Matches
Stabilizer.cpp
Go to the documentation of this file.
1
10// Copyright (c) 2008-2019 OpenShot Studios, LLC
11//
12// SPDX-License-Identifier: LGPL-3.0-or-later
13
14#include <fstream>
15#include <iomanip>
16#include <iostream>
17
18#include "effects/Stabilizer.h"
19#include "Exceptions.h"
20#include "stabilizedata.pb.h"
21
22#include <google/protobuf/util/time_util.h>
23
24#if CV_VERSION_MAJOR >= 5
25#define int64 opencv_broken_int
26#define uint64 opencv_broken_uint
27#include <opencv2/geometry/2d.hpp>
28#undef uint64
29#undef int64
30#else
31#include <opencv2/imgproc.hpp>
32#endif
33
34using namespace std;
35using namespace openshot;
36using google::protobuf::util::TimeUtil;
37
39Stabilizer::Stabilizer(std::string clipStabilizedDataPath):protobuf_data_path(clipStabilizedDataPath)
40{
41 // Init effect properties
42 init_effect_details();
43 // Tries to load the stabilization data from protobuf
44 LoadStabilizedData(clipStabilizedDataPath);
45}
46
47// Default constructor
49{
50 // Init effect properties
51 init_effect_details();
52}
53
54// Init effect settings
55void Stabilizer::init_effect_details()
56{
57
60
62 info.class_name = "Stabilizer";
63 info.name = "Stabilizer";
64 info.description = "Stabilize video clip to remove undesired shaking and jitter.";
65 info.has_audio = false;
66 info.has_video = true;
67 protobuf_data_path = "";
68 zoom = 1.0;
69}
70
71// This method is required for all derived classes of EffectBase, and returns a
72// modified openshot::Frame object
73std::shared_ptr<Frame> Stabilizer::GetFrame(std::shared_ptr<Frame> frame, int64_t frame_number)
74{
75
76 // Grab OpenCV Mat image
77 cv::Mat frame_image = frame->GetImageCV();
78
79 // If frame is NULL, return itself
80 if(!frame_image.empty()){
81
82 // Check if track data exists for the requested frame
83 if(transformationData.find(frame_number) != transformationData.end()){
84
85 float zoom_value = zoom.GetValue(frame_number);
86
87 // Create empty rotation matrix
88 cv::Mat T(2,3,CV_64F);
89
90 // Set rotation matrix values
91 T.at<double>(0,0) = cos(transformationData[frame_number].da);
92 T.at<double>(0,1) = -sin(transformationData[frame_number].da);
93 T.at<double>(1,0) = sin(transformationData[frame_number].da);
94 T.at<double>(1,1) = cos(transformationData[frame_number].da);
95
96 T.at<double>(0,2) = transformationData[frame_number].dx * frame_image.size().width;
97 T.at<double>(1,2) = transformationData[frame_number].dy * frame_image.size().height;
98
99 // Apply rotation matrix to image
100 cv::Mat frame_stabilized;
101 cv::warpAffine(frame_image, frame_stabilized, T, frame_image.size());
102
103 // Scale up the image to remove black borders
104 cv::Mat T_scale = cv::getRotationMatrix2D(cv::Point2f(frame_stabilized.cols/2, frame_stabilized.rows/2), 0, zoom_value);
105 cv::warpAffine(frame_stabilized, frame_stabilized, T_scale, frame_stabilized.size());
106 frame_image = frame_stabilized;
107 }
108 }
109 // Set stabilized image to frame
110 // If the input image is NULL or doesn't have tracking data, it's returned as it came
111 frame->SetImageCV(frame_image);
112 return frame;
113}
114
115// Load protobuf data file
116bool Stabilizer::LoadStabilizedData(std::string inputFilePath){
117 using std::ios;
118 // Create stabilization message
119 pb_stabilize::Stabilization stabilizationMessage;
120
121 // Read the existing tracker message.
122 std::fstream input(inputFilePath, ios::in | ios::binary);
123 if (!stabilizationMessage.ParseFromIstream(&input)) {
124 std::cerr << "Failed to parse protobuf message." << std::endl;
125 return false;
126 }
127
128 // Make sure the data maps are empty
129 transformationData.clear();
130 trajectoryData.clear();
131
132 // Iterate over all frames of the saved message and assign to the data maps
133 for (size_t i = 0; i < stabilizationMessage.frame_size(); i++) {
134
135 // Create stabilization message
136 const pb_stabilize::Frame& pbFrameData = stabilizationMessage.frame(i);
137
138 // Load frame number
139 size_t id = pbFrameData.id();
140
141 // Load camera trajectory data
142 float x = pbFrameData.x();
143 float y = pbFrameData.y();
144 float a = pbFrameData.a();
145
146 // Assign data to trajectory map
148
149 // Load transformation data
150 float dx = pbFrameData.dx();
151 float dy = pbFrameData.dy();
152 float da = pbFrameData.da();
153
154 // Assing data to transformation map
156 }
157
158 // Delete all global objects allocated by libprotobuf.
159 google::protobuf::ShutdownProtobufLibrary();
160
161 return true;
162}
163
164
165
166// Generate JSON string of this object
167std::string Stabilizer::Json() const {
168
169 // Return formatted string
170 return JsonValue().toStyledString();
171}
172
173// Generate Json::Value for this object
174Json::Value Stabilizer::JsonValue() const {
175
176 // Create root json object
177 Json::Value root = EffectBase::JsonValue(); // get parent properties
178 root["type"] = info.class_name;
179 root["protobuf_data_path"] = protobuf_data_path;
180 root["zoom"] = zoom.JsonValue();
181
182 // return JsonValue
183 return root;
184}
185
186// Load JSON string into this object
187void Stabilizer::SetJson(const std::string value) {
188 // Parse JSON string into JSON objects
189 try
190 {
191 const Json::Value root = openshot::stringToJson(value);
192 // Set all values that match
193
194 SetJsonValue(root);
195 }
196 catch (const std::exception& e)
197 {
198 // Error parsing JSON (or missing keys)
199 throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
200 }
201}
202
203// Load Json::Value into this object
204void Stabilizer::SetJsonValue(const Json::Value root) {
205
206 // Set parent data
208
209 // Set data from Json (if key is found)
210 if (!root["protobuf_data_path"].isNull()){
211 protobuf_data_path = (root["protobuf_data_path"].asString());
212
213 if(!LoadStabilizedData(protobuf_data_path)){
214 std::cout<<"Invalid protobuf data path";
215 protobuf_data_path = "";
216 }
217 }
218 if(!root["zoom"].isNull())
219 zoom.SetJsonValue(root["zoom"]);
220}
221
222// Get all properties for a specific frame
223std::string Stabilizer::PropertiesJSON(int64_t requested_frame) const {
224
225 // Generate JSON properties list
226 Json::Value root = BasePropertiesJSON(requested_frame);
227
228 root["zoom"] = add_property_json("Zoom", zoom.GetValue(requested_frame), "float", "", &zoom, 0.0, 2.0, false, requested_frame);
229
230 // Return formatted string
231 return root.toStyledString();
232}
Header file for all Exception classes.
Header file for Stabilizer effect class.
std::string id
ID Property for all derived Clip and Effect classes.
Definition ClipBase.h:34
Json::Value add_property_json(std::string name, float value, std::string type, std::string memo, const Keyframe *keyframe, float min_value, float max_value, bool readonly, int64_t requested_frame) const
Generate JSON for a property.
Definition ClipBase.cpp:100
virtual Json::Value JsonValue() const
Generate Json::Value for this object.
Json::Value BasePropertiesJSON(int64_t requested_frame) const
Generate JSON object of base properties (recommended to be used by all effects)
virtual void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
EffectInfoStruct info
Information about the current effect.
Definition EffectBase.h:114
Exception for invalid JSON.
Definition Exceptions.h:224
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition KeyFrame.cpp:372
double GetValue(int64_t index) const
Get the value at a specific index.
Definition KeyFrame.cpp:258
Json::Value JsonValue() const
Generate Json::Value for this object.
Definition KeyFrame.cpp:339
Json::Value JsonValue() const override
Generate Json::Value for this object.
std::shared_ptr< Frame > GetFrame(std::shared_ptr< Frame > frame, int64_t frame_number) override
This method is required for all derived classes of EffectBase, and returns a modified openshot::Frame...
std::map< size_t, EffectTransformParam > transformationData
Definition Stabilizer.h:77
std::string PropertiesJSON(int64_t requested_frame) const override
void SetJson(const std::string value) override
Load JSON string into this object.
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
std::map< size_t, EffectCamTrajectory > trajectoryData
Definition Stabilizer.h:76
bool LoadStabilizedData(std::string inputFilePath)
Load protobuf data file.
std::string Json() const override
Generate JSON string of this object.
This namespace is the default namespace for all code in the openshot library.
const Json::Value stringToJson(const std::string value)
Definition Json.cpp:16
bool has_video
Determines if this effect manipulates the image of a frame.
Definition EffectBase.h:43
bool has_audio
Determines if this effect manipulates the audio of a frame.
Definition EffectBase.h:44
std::string class_name
The class name of the effect.
Definition EffectBase.h:39
std::string name
The name of the effect.
Definition EffectBase.h:40
std::string description
The description of this effect and what it does.
Definition EffectBase.h:41