OpenShot Library | libopenshot  0.1.2
ChromaKey.cpp
Go to the documentation of this file.
1 /**
2  * @file
3  * @brief Source file for ChromaKey class
4  * @author Jonathan Thomas <jonathan@openshot.org>
5  *
6  * @section LICENSE
7  *
8  * Copyright (c) 2008-2014 OpenShot Studios, LLC
9  * <http://www.openshotstudios.com/>. This file is part of
10  * OpenShot Library (libopenshot), an open-source project dedicated to
11  * delivering high quality video editing and animation solutions to the
12  * world. For more information visit <http://www.openshot.org/>.
13  *
14  * OpenShot Library (libopenshot) is free software: you can redistribute it
15  * and/or modify it under the terms of the GNU Lesser General Public License
16  * as published by the Free Software Foundation, either version 3 of the
17  * License, or (at your option) any later version.
18  *
19  * OpenShot Library (libopenshot) is distributed in the hope that it will be
20  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22  * GNU Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public License
25  * along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
26  */
27 
28 #include "../../include/effects/ChromaKey.h"
29 
30 using namespace openshot;
31 
32 /// Blank constructor, useful when using Json to load the effect properties
33 ChromaKey::ChromaKey() : fuzz(5.0) {
34  // Init default color
35  color = Color();
36 
37  // Init effect properties
38  init_effect_details();
39 }
40 
41 // Default constructor, which takes an openshot::Color object and a 'fuzz' factor, which
42 // is used to determine how similar colored pixels are matched. The higher the fuzz, the
43 // more colors are matched.
44 ChromaKey::ChromaKey(Color color, Keyframe fuzz) : color(color), fuzz(fuzz)
45 {
46  // Init effect properties
47  init_effect_details();
48 }
49 
50 // Init effect settings
51 void ChromaKey::init_effect_details()
52 {
53  /// Initialize the values of the EffectInfo struct.
55 
56  /// Set the effect info
57  info.class_name = "ChromaKey";
58  info.name = "Chroma Key (Greenscreen)";
59  info.description = "Replaces the color (or chroma) of the frame with transparency (i.e. keys out the color).";
60  info.has_audio = false;
61  info.has_video = true;
62 }
63 
64 // This method is required for all derived classes of EffectBase, and returns a
65 // modified openshot::Frame object
66 tr1::shared_ptr<Frame> ChromaKey::GetFrame(tr1::shared_ptr<Frame> frame, long int frame_number)
67 {
68  // Determine the current HSL (Hue, Saturation, Lightness) for the Chrome
69  int threshold = fuzz.GetInt(frame_number);
70  long mask_R = color.red.GetInt(frame_number);
71  long mask_G = color.green.GetInt(frame_number);
72  long mask_B = color.blue.GetInt(frame_number);
73 
74  // Get source image's pixels
75  tr1::shared_ptr<QImage> image = frame->GetImage();
76  unsigned char *pixels = (unsigned char *) image->bits();
77 
78  // Loop through pixels
79  for (int pixel = 0, byte_index=0; pixel < image->width() * image->height(); pixel++, byte_index+=4)
80  {
81  // Get the RGB values from the pixel
82  unsigned char R = pixels[byte_index];
83  unsigned char G = pixels[byte_index + 1];
84  unsigned char B = pixels[byte_index + 2];
85  unsigned char A = pixels[byte_index + 3];
86 
87  // Get distance between mask color and pixel color
88  long distance = Color::GetDistance((long)R, (long)G, (long)B, mask_R, mask_G, mask_B);
89 
90  // Alpha out the pixel (if color similar)
91  if (distance <= threshold)
92  // MATCHED - Make pixel transparent
93  pixels[byte_index + 3] = 0;
94  }
95 
96  // return the modified frame
97  return frame;
98 }
99 
100 // Generate JSON string of this object
101 string ChromaKey::Json() {
102 
103  // Return formatted string
104  return JsonValue().toStyledString();
105 }
106 
107 // Generate Json::JsonValue for this object
108 Json::Value ChromaKey::JsonValue() {
109 
110  // Create root json object
111  Json::Value root = EffectBase::JsonValue(); // get parent properties
112  root["type"] = info.class_name;
113  root["color"] = color.JsonValue();
114  root["fuzz"] = fuzz.JsonValue();
115 
116  // return JsonValue
117  return root;
118 }
119 
120 // Load JSON string into this object
121 void ChromaKey::SetJson(string value) throw(InvalidJSON) {
122 
123  // Parse JSON string into JSON objects
124  Json::Value root;
125  Json::Reader reader;
126  bool success = reader.parse( value, root );
127  if (!success)
128  // Raise exception
129  throw InvalidJSON("JSON could not be parsed (or is invalid)", "");
130 
131  try
132  {
133  // Set all values that match
134  SetJsonValue(root);
135  }
136  catch (exception e)
137  {
138  // Error parsing JSON (or missing keys)
139  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)", "");
140  }
141 }
142 
143 // Load Json::JsonValue into this object
144 void ChromaKey::SetJsonValue(Json::Value root) {
145 
146  // Set parent data
148 
149  // Set data from Json (if key is found)
150  if (!root["color"].isNull())
151  color.SetJsonValue(root["color"]);
152  if (!root["fuzz"].isNull())
153  fuzz.SetJsonValue(root["fuzz"]);
154 }
155 
156 // Get all properties for a specific frame
157 string ChromaKey::PropertiesJSON(long int requested_frame) {
158 
159  // Requested Point
160  Point requested_point(requested_frame, requested_frame);
161 
162  // Generate JSON properties list
163  Json::Value root;
164  root["id"] = add_property_json("ID", 0.0, "string", Id(), false, 0, -1, -1, CONSTANT, -1, true);
165  root["position"] = add_property_json("Position", Position(), "float", "", false, 0, 0, 30 * 60 * 60 * 48, CONSTANT, -1, false);
166  root["layer"] = add_property_json("Track", Layer(), "int", "", false, 0, 0, 20, CONSTANT, -1, false);
167  root["start"] = add_property_json("Start", Start(), "float", "", false, 0, 0, 30 * 60 * 60 * 48, CONSTANT, -1, false);
168  root["end"] = add_property_json("End", End(), "float", "", false, 0, 0, 30 * 60 * 60 * 48, CONSTANT, -1, false);
169  root["duration"] = add_property_json("Duration", Duration(), "float", "", false, 0, 0, 30 * 60 * 60 * 48, CONSTANT, -1, true);
170 
171  // Keyframes
172  root["color"] = add_property_json("Key Color", 0.0, "color", "", color.red.Contains(requested_point), color.red.GetCount(), 0, 255, color.red.GetClosestPoint(requested_point).interpolation, color.red.GetClosestPoint(requested_point).co.X, false);
173  root["color"]["red"] = add_property_json("Red", color.red.GetValue(requested_frame), "float", "", color.red.Contains(requested_point), color.red.GetCount(), 0, 255, color.red.GetClosestPoint(requested_point).interpolation, color.red.GetClosestPoint(requested_point).co.X, false);
174  root["color"]["blue"] = add_property_json("Blue", color.blue.GetValue(requested_frame), "float", "", color.blue.Contains(requested_point), color.blue.GetCount(), 0, 255, color.blue.GetClosestPoint(requested_point).interpolation, color.blue.GetClosestPoint(requested_point).co.X, false);
175  root["color"]["green"] = add_property_json("Green", color.green.GetValue(requested_frame), "float", "", color.green.Contains(requested_point), color.green.GetCount(), 0, 255, color.green.GetClosestPoint(requested_point).interpolation, color.green.GetClosestPoint(requested_point).co.X, false);
176  root["fuzz"] = add_property_json("Fuzz", fuzz.GetValue(requested_frame), "float", "", fuzz.Contains(requested_point), fuzz.GetCount(), 0, 25, fuzz.GetClosestPoint(requested_point).interpolation, fuzz.GetClosestPoint(requested_point).co.X, false);
177 
178  // Return formatted string
179  return root.toStyledString();
180 }
string Json()
Get and Set JSON methods.
Definition: ChromaKey.cpp:101
Json::Value JsonValue()
Generate Json::JsonValue for this object.
Definition: ChromaKey.cpp:108
Json::Value JsonValue()
Generate Json::JsonValue for this object.
Definition: Color.cpp:92
Keyframe green
Curve representing the green value (0 - 255)
Definition: Color.h:46
Json::Value JsonValue()
Generate Json::JsonValue for this object.
Definition: KeyFrame.cpp:319
void SetJson(string value)
Load JSON string into this object.
Definition: ChromaKey.cpp:121
InterpolationType interpolation
This is the interpolation mode.
Definition: Point.h:86
Keyframe red
Curve representing the red value (0 - 255)
Definition: Color.h:45
bool Contains(Point p)
Does this keyframe contain a specific point.
Definition: KeyFrame.cpp:175
float End()
Get end position (in seconds) of clip (trim end of video)
Definition: ClipBase.h:80
A Point is the basic building block of a key-frame curve.
Definition: Point.h:81
int Layer()
Get layer of clip on timeline (lower number is covered by higher numbers)
Definition: ClipBase.h:78
string class_name
The class name of the effect.
Definition: EffectBase.h:51
virtual Json::Value JsonValue()=0
Generate Json::JsonValue for this object.
Definition: EffectBase.cpp:69
void SetJsonValue(Json::Value root)
Load Json::JsonValue into this object.
Definition: KeyFrame.cpp:360
bool has_audio
Determines if this effect manipulates the audio of a frame.
Definition: EffectBase.h:56
static long GetDistance(long R1, long G1, long B1, long R2, long G2, long B2)
Get the distance between 2 RGB pairs. (0=identical colors, 10=very close colors, 760=very different c...
Definition: Color.cpp:75
float GetValue(long int index)
Get the value at a specific index.
Definition: KeyFrame.cpp:224
void SetJsonValue(Json::Value root)
Load Json::JsonValue into this object.
Definition: ChromaKey.cpp:144
Keyframe blue
Curve representing the red value (0 - 255)
Definition: Color.h:47
Json::Value add_property_json(string name, float value, string type, string memo, bool contains_point, int number_of_points, float min_value, float max_value, InterpolationType intepolation, int closest_point_x, bool readonly)
Generate JSON for a property.
Definition: ClipBase.cpp:65
string Id()
Get basic properties.
Definition: ClipBase.h:76
ChromaKey()
Blank constructor, useful when using Json to load the effect properties.
Definition: ChromaKey.cpp:33
float Position()
Get position on timeline (in seconds)
Definition: ClipBase.h:77
string name
The name of the effect.
Definition: EffectBase.h:53
string PropertiesJSON(long int requested_frame)
Definition: ChromaKey.cpp:157
string description
The description of this effect and what it does.
Definition: EffectBase.h:54
virtual void SetJsonValue(Json::Value root)=0
Load Json::JsonValue into this object.
Definition: EffectBase.cpp:109
float X
The X value of the coordinate (usually representing the frame #)
Definition: Coordinate.h:61
Point GetClosestPoint(Point p)
Get current point (or closest point) from the X coordinate (i.e. the frame number) ...
Definition: KeyFrame.cpp:193
tr1::shared_ptr< Frame > GetFrame(tr1::shared_ptr< Frame > frame, long int frame_number)
This method is required for all derived classes of EffectBase, and returns a modified openshot::Frame...
Definition: ChromaKey.cpp:66
This class represents a color (used on the timeline and clips)
Definition: Color.h:42
int GetInt(long int index)
Get the rounded INT value at a specific index.
Definition: KeyFrame.cpp:246
This namespace is the default namespace for all code in the openshot library.
long int GetCount()
Get the number of points (i.e. # of points)
Definition: KeyFrame.cpp:453
Coordinate co
This is the primary coordinate.
Definition: Point.h:83
bool has_video
Determines if this effect manipulates the image of a frame.
Definition: EffectBase.h:55
Exception for invalid JSON.
Definition: Exceptions.h:152
void SetJsonValue(Json::Value root)
Load Json::JsonValue into this object.
Definition: Color.cpp:129
A Keyframe is a collection of Point instances, which is used to vary a number or property over time...
Definition: KeyFrame.h:64
float Duration()
Get the length of this clip (in seconds)
Definition: ClipBase.h:81
Constant curves jump from their previous position to a new one (with no interpolation).
Definition: Point.h:48
float Start()
Get start position (in seconds) of clip (trim start of video)
Definition: ClipBase.h:79
EffectInfoStruct info
Information about the current effect.
Definition: EffectBase.h:73