Commit eb77145ebb0cb9c69a4eb58039087eb114c21fec

Authored by Brendan Klare
1 parent 66182936

Resize with padding to preserve aspect ratio

Showing 1 changed file with 22 additions and 1 deletions
openbr/plugins/crop.cpp
... ... @@ -113,6 +113,8 @@ BR_REGISTER(Transform, ROIFromPtsTransform)
113 113 * \brief Resize the template
114 114 * \author Josh Klontz \cite jklontz
115 115 * \note Method: Area should be used for shrinking an image, Cubic for slow but accurate enlargment, Bilin for fast enlargement.
  116 + * \param preserveAspect If true, the image will be sized per specification, but
  117 + * a border will be applied to preserve aspect ratio.
116 118 */
117 119 class ResizeTransform : public UntrainableTransform
118 120 {
... ... @@ -131,13 +133,32 @@ private:
131 133 Q_PROPERTY(int rows READ get_rows WRITE set_rows RESET reset_rows STORED false)
132 134 Q_PROPERTY(int columns READ get_columns WRITE set_columns RESET reset_columns STORED false)
133 135 Q_PROPERTY(Method method READ get_method WRITE set_method RESET reset_method STORED false)
  136 + Q_PROPERTY(bool preserveAspect READ get_preserveAspect WRITE set_preserveAspect RESET reset_preserveAspect STORED false)
134 137 BR_PROPERTY(int, rows, -1)
135 138 BR_PROPERTY(int, columns, -1)
136 139 BR_PROPERTY(Method, method, Bilin)
  140 + BR_PROPERTY(bool, preserveAspect, false)
137 141  
138 142 void project(const Template &src, Template &dst) const
139 143 {
140   - resize(src, dst, Size((columns == -1) ? src.m().cols*rows/src.m().rows : columns, rows), 0, 0, method);
  144 + if (!preserveAspect)
  145 + resize(src, dst, Size((columns == -1) ? src.m().cols*rows/src.m().rows : columns, rows), 0, 0, method);
  146 + else {
  147 + float inRatio = (float) src.m().rows / src.m().cols;
  148 + float outRatio = (float) rows / columns;
  149 + dst = Mat::zeros(rows, columns, src.m().type());
  150 + if (outRatio > inRatio) {
  151 + float heightAR = src.m().rows * inRatio / outRatio;
  152 + Mat buffer;
  153 + resize(src, buffer, Size(columns, heightAR), 0, 0, method);
  154 + buffer.copyTo(dst.m()(Rect(0, (rows - heightAR) / 2, columns, heightAR)));
  155 + } else {
  156 + float widthAR = src.m().cols / inRatio * outRatio;
  157 + Mat buffer;
  158 + resize(src, buffer, Size(widthAR, rows), 0, 0, method);
  159 + buffer.copyTo(dst.m()(Rect((columns - widthAR) / 2, 0, widthAR, rows)));
  160 + }
  161 + }
141 162 }
142 163 };
143 164  
... ...