OpenShot Library | libopenshot  0.1.9
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 std::shared_ptr<Frame> ChromaKey::GetFrame(std::shared_ptr<Frame> frame, int64_t 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  std::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) {
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(int64_t requested_frame) {
158 
159  // Generate JSON properties list
160  Json::Value root;
161  root["id"] = add_property_json("ID", 0.0, "string", Id(), NULL, -1, -1, true, requested_frame);
162  root["position"] = add_property_json("Position", Position(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
163  root["layer"] = add_property_json("Track", Layer(), "int", "", NULL, 0, 20, false, requested_frame);
164  root["start"] = add_property_json("Start", Start(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
165  root["end"] = add_property_json("End", End(), "float", "", NULL, 0, 30 * 60 * 60 * 48, false, requested_frame);
166  root["duration"] = add_property_json("Duration", Duration(), "float", "", NULL, 0, 30 * 60 * 60 * 48, true, requested_frame);
167 
168  // Keyframes
169  root["color"] = add_property_json("Key Color", 0.0, "color", "", NULL, 0, 255, false, requested_frame);
170  root["color"]["red"] = add_property_json("Red", color.red.GetValue(requested_frame), "float", "", &color.red, 0, 255, false, requested_frame);
171  root["color"]["blue"] = add_property_json("Blue", color.blue.GetValue(requested_frame), "float", "", &color.blue, 0, 255, false, requested_frame);
172  root["color"]["green"] = add_property_json("Green", color.green.GetValue(requested_frame), "float", "", &color.green, 0, 255, false, requested_frame);
173  root["fuzz"] = add_property_json("Fuzz", fuzz.GetValue(requested_frame), "float", "", &fuzz, 0, 25, false, requested_frame);
174 
175  // Return formatted string
176  return root.toStyledString();
177 }
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:321
void SetJson(string value)
Load JSON string into this object.
Definition: ChromaKey.cpp:121
Keyframe red
Curve representing the red value (0 - 255)
Definition: Color.h:45
std::shared_ptr< Frame > GetFrame(std::shared_ptr< Frame > frame, int64_t frame_number)
This method is required for all derived classes of EffectBase, and returns a modified openshot::Frame...
Definition: ChromaKey.cpp:66
float End()
Get end position (in seconds) of clip (trim end of video)
Definition: ClipBase.h:86
Json::Value add_property_json(string name, float value, string type, string memo, Keyframe *keyframe, float min_value, float max_value, bool readonly, int64_t requested_frame)
Generate JSON for a property.
Definition: ClipBase.cpp:65
int Layer()
Get layer of clip on timeline (lower number is covered by higher numbers)
Definition: ClipBase.h:84
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:362
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
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
string Id()
Get basic properties.
Definition: ClipBase.h:82
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:83
string name
The name of the effect.
Definition: EffectBase.h:53
string PropertiesJSON(int64_t 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
int GetInt(int64_t index)
Get the rounded INT value at a specific index.
Definition: KeyFrame.cpp:248
This class represents a color (used on the timeline and clips)
Definition: Color.h:42
double GetValue(int64_t index)
Get the value at a specific index.
Definition: KeyFrame.cpp:226
This namespace is the default namespace for all code in the openshot library.
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:87
float Start()
Get start position (in seconds) of clip (trim start of video)
Definition: ClipBase.h:85
EffectInfoStruct info
Information about the current effect.
Definition: EffectBase.h:73