Merge pull request #3234 from Carbenium/poly

Rework API of geometry classes
This commit is contained in:
Isaac Connor 2021-05-16 13:53:20 -04:00 committed by GitHub
commit 23312a36b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 722 additions and 466 deletions

View File

@ -6,12 +6,10 @@ configure_file(zm_config_data.h.in "${CMAKE_BINARY_DIR}/zm_config_data.h" @ONLY)
# Group together all the source files that are used by all the binaries (zmc, zmu, zms etc)
set(ZM_BIN_SRC_FILES
zm_analysis_thread.cpp
zm_box.cpp
zm_buffer.cpp
zm_camera.cpp
zm_comms.cpp
zm_config.cpp
zm_coord.cpp
zm_curl_camera.cpp
zm_crypt.cpp
zm.cpp

View File

@ -1,22 +0,0 @@
//
// ZoneMinder Box Class Implementation, $Date$, $Revision$
// Copyright (C) 2001-2008 Philip Coombes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#include "zm_box.h"
// This section deliberately left blank

View File

@ -20,49 +20,59 @@
#ifndef ZM_BOX_H
#define ZM_BOX_H
#include "zm_coord.h"
#include "zm_line.h"
#include "zm_vector2.h"
#include <cmath>
#include <vector>
//
// Class used for storing a box, which is defined as a region
// defined by two coordinates
//
class Box {
private:
Coord lo, hi;
Coord size;
public:
Box() = default;
Box(Vector2 lo, Vector2 hi) : lo_(lo), hi_(hi), size_(hi - lo) {}
public:
inline Box() : lo(0,0), hi(0,0), size(0,0) { }
explicit inline Box(unsigned int p_size) : lo(0, 0), hi(p_size-1, p_size-1), size(Coord::Range(hi, lo)) { }
inline Box( int p_x_size, int p_y_size ) : lo( 0, 0 ), hi ( p_x_size-1, p_y_size-1 ), size( Coord::Range( hi, lo ) ) { }
inline Box( int lo_x, int lo_y, int hi_x, int hi_y ) : lo( lo_x, lo_y ), hi( hi_x, hi_y ), size( Coord::Range( hi, lo ) ) { }
inline Box( const Coord &p_lo, const Coord &p_hi ) : lo( p_lo ), hi( p_hi ), size( Coord::Range( hi, lo ) ) { }
const Vector2 &Lo() const { return lo_; }
const Vector2 &Hi() const { return hi_; }
inline const Coord &Lo() const { return lo; }
inline int LoX() const { return lo.X(); }
inline int LoX(int p_lo_x) { return lo.X(p_lo_x); }
inline int LoY() const { return lo.Y(); }
inline int LoY(int p_lo_y) { return lo.Y(p_lo_y); }
inline const Coord &Hi() const { return hi; }
inline int HiX() const { return hi.X(); }
inline int HiX(int p_hi_x) { return hi.X(p_hi_x); }
inline int HiY() const { return hi.Y(); }
inline int HiY(int p_hi_y) { return hi.Y(p_hi_y); }
inline const Coord &Size() const { return size; }
inline int Width() const { return size.X(); }
inline int Height() const { return size.Y(); }
inline int Area() const { return size.X()*size.Y(); }
const Vector2 &Size() const { return size_; }
int32 Area() const { return size_.x_ * size_.y_; }
inline const Coord Centre() const {
int mid_x = int(std::round(lo.X()+(size.X()/2.0)));
int mid_y = int(std::round(lo.Y()+(size.Y()/2.0)));
return Coord( mid_x, mid_y );
Vector2 Centre() const {
int32 mid_x = static_cast<int32>(std::lround(lo_.x_ + (size_.x_ / 2.0)));
int32 mid_y = static_cast<int32>(std::lround(lo_.y_ + (size_.y_ / 2.0)));
return {mid_x, mid_y};
}
inline bool Inside( const Coord &coord ) const
{
return( coord.X() >= lo.X() && coord.X() <= hi.X() && coord.Y() >= lo.Y() && coord.Y() <= hi.Y() );
// Get vertices of the box in a counter-clockwise order
std::vector<Vector2> Vertices() const {
return {lo_, {hi_.x_, lo_.y_}, hi_, {lo_.x_, hi_.y_}};
}
// Get edges of the box in a counter-clockwise order
std::vector<LineSegment> Edges() const {
std::vector<LineSegment> edges;
edges.reserve(4);
std::vector<Vector2> v = Vertices();
edges.emplace_back(v[0], v[1]);
edges.emplace_back(v[1], v[2]);
edges.emplace_back(v[2], v[3]);
edges.emplace_back(v[3], v[0]);
return edges;
}
bool Contains(const Vector2 &coord) const {
return (coord.x_ >= lo_.x_ && coord.x_ <= hi_.x_ && coord.y_ >= lo_.y_ && coord.y_ <= hi_.y_);
}
private:
Vector2 lo_;
Vector2 hi_;
Vector2 size_;
};
#endif // ZM_BOX_H

View File

@ -1,22 +0,0 @@
//
// ZoneMinder Coordinate Class Implementation, $Date$, $Revision$
// Copyright (C) 2001-2008 Philip Coombes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#include "zm_coord.h"
// This section deliberately left blank

View File

@ -1,64 +0,0 @@
//
// ZoneMinder Coordinate Class Interface, $Date$, $Revision$
// Copyright (C) 2001-2008 Philip Coombes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#ifndef ZM_COORD_H
#define ZM_COORD_H
#include "zm_define.h"
//
// Class used for storing an x,y pair, i.e. a coordinate
//
class Coord {
private:
int x, y;
public:
inline Coord() : x(0), y(0) { }
inline Coord( int p_x, int p_y ) : x(p_x), y(p_y) { }
inline Coord( const Coord &p_coord ) : x(p_coord.x), y(p_coord.y) { }
inline Coord &operator =( const Coord &coord ) {
x = coord.x;
y = coord.y;
return *this;
}
inline int &X(int p_x) { x=p_x; return x; }
inline const int &X() const { return x; }
inline int &Y(int p_y) { y=p_y; return y; }
inline const int &Y() const { return y; }
inline static Coord Range( const Coord &coord1, const Coord &coord2 ) {
Coord result( (coord1.x-coord2.x)+1, (coord1.y-coord2.y)+1 );
return result;
}
inline bool operator==( const Coord &coord ) const { return( x == coord.x && y == coord.y ); }
inline bool operator!=( const Coord &coord ) const { return( x != coord.x || y != coord.y ); }
inline bool operator>( const Coord &coord ) const { return( x > coord.x && y > coord.y ); }
inline bool operator>=( const Coord &coord ) const { return( !(operator<(coord)) ); }
inline bool operator<( const Coord &coord ) const { return( x < coord.x && y < coord.y ); }
inline bool operator<=( const Coord &coord ) const { return( !(operator>(coord)) ); }
inline Coord &operator+=( const Coord &coord ) { x += coord.x; y += coord.y; return( *this ); }
inline Coord &operator-=( const Coord &coord ) { x -= coord.x; y -= coord.y; return( *this ); }
inline friend Coord operator+( const Coord &coord1, const Coord &coord2 ) { Coord result( coord1 ); result += coord2; return( result ); }
inline friend Coord operator-( const Coord &coord1, const Coord &coord2 ) { Coord result( coord1 ); result -= coord2; return( result ); }
};
#endif // ZM_COORD_H

View File

@ -29,6 +29,7 @@
#endif
#include <cinttypes>
#include <cstddef>
typedef std::int64_t int64;
typedef std::int32_t int32;

View File

@ -473,10 +473,10 @@ void Event::WriteDbFrames() {
stats.alarm_blobs_,
stats.min_blob_size_,
stats.max_blob_size_,
stats.alarm_box_.LoX(),
stats.alarm_box_.LoY(),
stats.alarm_box_.HiX(),
stats.alarm_box_.HiY(),
stats.alarm_box_.Lo().x_,
stats.alarm_box_.Lo().y_,
stats.alarm_box_.Hi().x_,
stats.alarm_box_.Hi().y_,
stats.score_);
} // end foreach zone stats
} // end if recording stats

View File

@ -250,7 +250,7 @@ int Image::PopulateFrame(AVFrame *frame) {
width, height, linesize, colours, size,
av_get_pix_fmt_name(imagePixFormat)
);
AVBufferRef *ref = av_buffer_create(buffer, size,
AVBufferRef *ref = av_buffer_create(buffer, size,
dont_free, /* Free callback */
nullptr, /* opaque */
0 /* flags */
@ -576,7 +576,7 @@ void Image::Initialise() {
if ( res == FontLoadError::kFileNotFound ) {
Panic("Invalid font location: %s", config.font_file_location);
} else if ( res == FontLoadError::kInvalidFile ) {
Panic("Invalid font file.");
Panic("Invalid font file.");
}
initialised = true;
}
@ -781,7 +781,7 @@ void Image::Assign(const Image &image) {
return;
}
} else {
if ( new_size > allocation || !buffer ) {
if (new_size > allocation || !buffer) {
// DumpImgBuffer(); This is also done in AllocImgBuffer
AllocImgBuffer(new_size);
}
@ -820,10 +820,10 @@ Image *Image::HighlightEdges(
/* Set image to all black */
high_image->Clear();
unsigned int lo_x = limits ? limits->Lo().X() : 0;
unsigned int lo_y = limits ? limits->Lo().Y() : 0;
unsigned int hi_x = limits ? limits->Hi().X() : width-1;
unsigned int hi_y = limits ? limits->Hi().Y() : height-1;
unsigned int lo_x = limits ? limits->Lo().x_ : 0;
unsigned int lo_y = limits ? limits->Lo().y_ : 0;
unsigned int hi_x = limits ? limits->Hi().x_ : width - 1;
unsigned int hi_y = limits ? limits->Hi().y_ : height - 1;
if ( p_colours == ZM_COLOUR_GRAY8 ) {
for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
@ -1508,7 +1508,7 @@ bool Image::Crop( unsigned int lo_x, unsigned int lo_y, unsigned int hi_x, unsig
}
bool Image::Crop(const Box &limits) {
return Crop(limits.LoX(), limits.LoY(), limits.HiX(), limits.HiY());
return Crop(limits.Lo().x_, limits.Lo().y_, limits.Hi().x_, limits.Hi().y_);
}
/* Far from complete */
@ -1932,7 +1932,7 @@ void Image::Delta(const Image &image, Image* targetimage) const {
#endif
}
const Coord Image::centreCoord( const char *text, int size=1 ) const {
const Vector2 Image::centreCoord(const char *text, int size = 1) const {
int index = 0;
int line_no = 0;
int text_len = strlen(text);
@ -1957,7 +1957,7 @@ const Coord Image::centreCoord( const char *text, int size=1 ) const {
uint16_t char_height = font_variant.GetCharHeight();
int x = (width - (max_line_len * char_width )) / 2;
int y = (height - (line_no * char_height) ) / 2;
return Coord(x, y);
return {x, y};
}
/* RGB32 compatible: complete */
@ -2007,7 +2007,7 @@ https://lemire.me/blog/2018/02/21/iterating-over-set-bits-quickly/
*/
void Image::Annotate(
const std::string &text,
const Coord &coord,
const Vector2 &coord,
const uint8 size,
const Rgb fg_colour,
const Rgb bg_colour) {
@ -2031,8 +2031,8 @@ void Image::Annotate(
// Calculate initial coordinates of annotation so that everything is displayed even if the
// user set coordinates would prevent that.
uint32 x0 = ZM::clamp(static_cast<uint32>(coord.X()), 0u, x0_max);
uint32 y0 = ZM::clamp(static_cast<uint32>(coord.Y()), 0u, y0_max);
uint32 x0 = ZM::clamp(static_cast<uint32>(coord.x_), 0u, x0_max);
uint32 y0 = ZM::clamp(static_cast<uint32>(coord.y_), 0u, y0_max);
uint32 y = y0;
for (const std::string &line : lines) {
@ -2127,7 +2127,7 @@ void Image::Annotate(
}
}
void Image::Timestamp( const char *label, const time_t when, const Coord &coord, const int size ) {
void Image::Timestamp(const char *label, const time_t when, const Vector2 &coord, const int size) {
char time_text[64];
tm when_tm = {};
strftime(time_text, sizeof(time_text), "%y/%m/%d %H:%M:%S", localtime_r(&when, &when_tm));
@ -2294,10 +2294,10 @@ void Image::Fill( Rgb colour, const Box *limits ) {
/* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour,subpixelorder);
unsigned int lo_x = limits?limits->Lo().X():0;
unsigned int lo_y = limits?limits->Lo().Y():0;
unsigned int hi_x = limits?limits->Hi().X():width-1;
unsigned int hi_y = limits?limits->Hi().Y():height-1;
unsigned int lo_x = limits ? limits->Lo().x_ : 0;
unsigned int lo_y = limits ? limits->Lo().y_ : 0;
unsigned int hi_x = limits ? limits->Hi().x_ : width - 1;
unsigned int hi_y = limits ? limits->Hi().y_ : height - 1;
if ( colours == ZM_COLOUR_GRAY8 ) {
for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
unsigned char *p = &buffer[(y*width)+lo_x];
@ -2339,10 +2339,10 @@ void Image::Fill( Rgb colour, int density, const Box *limits ) {
/* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour, subpixelorder);
unsigned int lo_x = limits?limits->Lo().X():0;
unsigned int lo_y = limits?limits->Lo().Y():0;
unsigned int hi_x = limits?limits->Hi().X():width-1;
unsigned int hi_y = limits?limits->Hi().Y():height-1;
unsigned int lo_x = limits ? limits->Lo().x_ : 0;
unsigned int lo_y = limits ? limits->Lo().y_ : 0;
unsigned int hi_x = limits ? limits->Hi().x_ : width - 1;
unsigned int hi_y = limits ? limits->Hi().y_ : height - 1;
if ( colours == ZM_COLOUR_GRAY8 ) {
for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
unsigned char *p = &buffer[(y*width)+lo_x];
@ -2382,17 +2382,18 @@ void Image::Outline( Rgb colour, const Polygon &polygon ) {
}
/* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour,subpixelorder);
colour = rgb_convert(colour, subpixelorder);
int n_coords = polygon.getNumCoords();
for ( int j = 0, i = n_coords-1; j < n_coords; i = j++ ) {
const Coord &p1 = polygon.getCoord( i );
const Coord &p2 = polygon.getCoord( j );
size_t n_coords = polygon.GetVertices().size();
for (size_t j = 0, i = n_coords - 1; j < n_coords; i = j++) {
const Vector2 &p1 = polygon.GetVertices()[i];
const Vector2 &p2 = polygon.GetVertices()[j];
int x1 = p1.X();
int x2 = p2.X();
int y1 = p1.Y();
int y2 = p2.Y();
// The last pixel we can draw is width/height - 1. Clamp to that value.
int x1 = ZM::clamp(p1.x_, 0, static_cast<int>(width - 1));
int x2 = ZM::clamp(p2.x_, 0, static_cast<int>(width - 1));
int y1 = ZM::clamp(p1.y_, 0, static_cast<int>(height - 1));
int y2 = ZM::clamp(p2.y_, 0, static_cast<int>(height - 1));
double dx = x2 - x1;
double dy = y2 - y1;
@ -2466,17 +2467,17 @@ void Image::Fill(Rgb colour, int density, const Polygon &polygon) {
/* Convert the colour's RGBA subpixel order into the image's subpixel order */
colour = rgb_convert(colour, subpixelorder);
int n_coords = polygon.getNumCoords();
size_t n_coords = polygon.GetVertices().size();
int n_global_edges = 0;
Edge global_edges[n_coords];
for ( int j = 0, i = n_coords-1; j < n_coords; i = j++ ) {
const Coord &p1 = polygon.getCoord(i);
const Coord &p2 = polygon.getCoord(j);
for (size_t j = 0, i = n_coords - 1; j < n_coords; i = j++) {
const Vector2 &p1 = polygon.GetVertices()[i];
const Vector2 &p2 = polygon.GetVertices()[j];
int x1 = p1.X();
int x2 = p2.X();
int y1 = p1.Y();
int y2 = p2.Y();
int x1 = p1.x_;
int x2 = p2.x_;
int y1 = p1.y_;
int y2 = p2.y_;
//Debug( 9, "x1:%d,y1:%d x2:%d,y2:%d", x1, y1, x2, y2 );
if ( y1 == y2 )
@ -2511,8 +2512,7 @@ void Image::Fill(Rgb colour, int density, const Polygon &polygon) {
Debug(9, "Moving global edge");
active_edges[n_active_edges++] = global_edges[i];
if ( i < (n_global_edges-1) ) {
//memcpy( &global_edges[i], &global_edges[i+1], sizeof(*global_edges)*(n_global_edges-i) );
memmove( &global_edges[i], &global_edges[i+1], sizeof(*global_edges)*(n_global_edges-i) );
memmove(&global_edges[i], &global_edges[i + 1], sizeof(*global_edges) * (n_global_edges - i - 1));
i--;
}
n_global_edges--;

View File

@ -20,19 +20,18 @@
#ifndef ZM_IMAGE_H
#define ZM_IMAGE_H
#include "zm_coord.h"
#include "zm_ffmpeg.h"
#include "zm_jpeg.h"
#include "zm_logger.h"
#include "zm_mem_utils.h"
#include "zm_rgb.h"
#include "zm_vector2.h"
#if HAVE_ZLIB_H
#include <zlib.h>
#endif // HAVE_ZLIB_H
class Box;
class Image;
class Polygon;
#define ZM_BUFTYPE_DONTFREE 0
@ -96,24 +95,6 @@ class Image {
void update_function_pointers();
protected:
struct Edge {
int min_y;
int max_y;
double min_x;
double _1_m;
static bool CompareYX(const Edge &e1, const Edge &e2) {
if ( e1.min_y == e2.min_y )
return e1.min_x < e2.min_x;
return e1.min_y < e2.min_y;
}
static bool CompareX(const Edge &e1, const Edge &e2) {
return e1.min_x < e2.min_x;
}
};
inline void AllocImgBuffer(size_t p_bufsize) {
if ( buffer )
DumpImgBuffer();
@ -280,16 +261,16 @@ class Image {
//Image *Delta( const Image &image ) const;
void Delta( const Image &image, Image* targetimage) const;
const Coord centreCoord(const char *text, const int size) const;
const Vector2 centreCoord(const char *text, const int size) const;
void MaskPrivacy( const unsigned char *p_bitmask, const Rgb pixel_colour=0x00222222 );
void Annotate(const std::string &text,
const Coord &coord,
const Vector2 &coord,
uint8 size = 1,
Rgb fg_colour = kRGBWhite,
Rgb bg_colour = kRGBBlack);
Image *HighlightEdges( Rgb colour, unsigned int p_colours, unsigned int p_subpixelorder, const Box *limits=0 );
//Image *HighlightEdges( Rgb colour, const Polygon &polygon );
void Timestamp( const char *label, const time_t when, const Coord &coord, const int size );
void Timestamp(const char *label, const time_t when, const Vector2 &coord, const int size);
void Colourise(const unsigned int p_reqcolours, const unsigned int p_reqsubpixelorder);
void DeColourise();

64
src/zm_line.h Normal file
View File

@ -0,0 +1,64 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ZONEMINDER_SRC_ZM_LINE_H_
#define ZONEMINDER_SRC_ZM_LINE_H_
#include "zm_vector2.h"
// Represents a part of a line bounded by two end points
class LineSegment {
public:
LineSegment(Vector2 start, Vector2 end) : start_(start), end_(end) {}
public:
Vector2 start_;
Vector2 end_;
};
// Represents an infinite line
class Line {
public:
Line(Vector2 p1, Vector2 p2) : position_(p1), direction_(p2 - p1) {}
explicit Line(LineSegment segment) : Line(segment.start_, segment.end_) {};
bool IsPointLeftOfOrColinear(Vector2 p) const {
int32 det = direction_.Determinant(p - position_);
return det >= 0;
}
Vector2 Intersection(Line const &line) const {
int32 det = direction_.Determinant(line.direction_);
if (det == 0) {
// lines are parallel or overlap, no intersection
return Vector2::Inf();
}
Vector2 c = line.position_ - position_;
double t = c.Determinant(line.direction_) / static_cast<double>(det);
return position_ + direction_ * t;
}
private:
Vector2 position_;
Vector2 direction_;
};
#endif //ZONEMINDER_SRC_ZM_LINE_H_

View File

@ -327,7 +327,7 @@ Monitor::Monitor()
record_audio(0),
//event_prefix
//label_format
label_coord(Coord(0,0)),
label_coord(Vector2(0,0)),
label_size(0),
image_buffer_count(0),
max_image_buffer_count(0),
@ -561,7 +561,7 @@ void Monitor::Load(MYSQL_ROW dbrow, bool load_zones=true, Purpose p = QUERY) {
/* "EventPrefix, LabelFormat, LabelX, LabelY, LabelSize," */
event_prefix = dbrow[col] ? dbrow[col] : ""; col++;
label_format = dbrow[col] ? ReplaceAll(dbrow[col], "\\n", "\n") : ""; col++;
label_coord = Coord(atoi(dbrow[col]), atoi(dbrow[col+1])); col += 2;
label_coord = Vector2(atoi(dbrow[col]), atoi(dbrow[col + 1])); col += 2;
label_size = atoi(dbrow[col]); col++;
/* "ImageBufferCount, `MaxImageBufferCount`, WarmupCount, PreEventCount, PostEventCount, StreamReplayBuffer, AlarmFrameCount, " */
@ -1481,21 +1481,27 @@ void Monitor::DumpZoneImage(const char *zone_string) {
zone_image->Colourise(ZM_COLOUR_RGB24, ZM_SUBPIX_ORDER_RGB);
}
extra_zone.Clip(Box(
{0, 0},
{static_cast<int32>(zone_image->Width()), static_cast<int32>(zone_image->Height())}
));
for (const Zone &zone : zones) {
if ( exclude_id && (!extra_colour || extra_zone.getNumCoords()) && zone.Id() == exclude_id )
if (exclude_id && (!extra_colour || !extra_zone.GetVertices().empty()) && zone.Id() == exclude_id) {
continue;
}
Rgb colour;
if ( exclude_id && !extra_zone.getNumCoords() && zone.Id() == exclude_id ) {
if (exclude_id && extra_zone.GetVertices().empty() && zone.Id() == exclude_id) {
colour = extra_colour;
} else {
if ( zone.IsActive() ) {
if (zone.IsActive()) {
colour = kRGBRed;
} else if ( zone.IsInclusive() ) {
} else if (zone.IsInclusive()) {
colour = kRGBOrange;
} else if ( zone.IsExclusive() ) {
} else if (zone.IsExclusive()) {
colour = kRGBPurple;
} else if ( zone.IsPreclusive() ) {
} else if (zone.IsPreclusive()) {
colour = kRGBBlue;
} else {
colour = kRGBWhite;
@ -1505,7 +1511,7 @@ void Monitor::DumpZoneImage(const char *zone_string) {
zone_image->Outline(colour, zone.GetPolygon());
}
if ( extra_zone.getNumCoords() ) {
if (!extra_zone.GetVertices().empty()) {
zone_image->Fill(extra_colour, 2, extra_zone);
zone_image->Outline(extra_colour, extra_zone);
}
@ -1544,8 +1550,9 @@ bool Monitor::CheckSignal(const Image *image) {
if ( !config.timestamp_on_capture || !label_format[0] )
break;
// Avoid sampling the rows with timestamp in
if ( index < (label_coord.Y()*width) || index >= (label_coord.Y()+Image::LINE_HEIGHT)*width )
if (index < (label_coord.y_ * width) || index >= (label_coord.y_ + Image::LINE_HEIGHT) * width) {
break;
}
}
if ( colours == ZM_COLOUR_GRAY8 ) {
@ -2832,7 +2839,7 @@ unsigned int Monitor::DetectMotion(const Image &comp_image, Event::StringSet &zo
} // end if CheckAlarms
} // end foreach zone
Coord alarm_centre;
Vector2 alarm_centre;
int top_score = -1;
if (alarm) {
@ -2898,8 +2905,8 @@ unsigned int Monitor::DetectMotion(const Image &comp_image, Event::StringSet &zo
} // end if alarm
if (top_score > 0) {
shared_data->alarm_x = alarm_centre.X();
shared_data->alarm_y = alarm_centre.Y();
shared_data->alarm_x = alarm_centre.x_;
shared_data->alarm_y = alarm_centre.y_;
Info("Got alarm centre at %d,%d, at count %d",
shared_data->alarm_x, shared_data->alarm_y, analysis_image_count);
@ -2954,7 +2961,7 @@ bool Monitor::DumpSettings(char *output, bool verbose) {
sprintf(output+strlen(output), "Subpixel Order : %u\n", camera->SubpixelOrder() );
sprintf(output+strlen(output), "Event Prefix : %s\n", event_prefix.c_str() );
sprintf(output+strlen(output), "Label Format : %s\n", label_format.c_str() );
sprintf(output+strlen(output), "Label Coord : %d,%d\n", label_coord.X(), label_coord.Y() );
sprintf(output+strlen(output), "Label Coord : %d,%d\n", label_coord.x_, label_coord.y_ );
sprintf(output+strlen(output), "Label Size : %d\n", label_size );
sprintf(output+strlen(output), "Image Buffer Count : %d\n", image_buffer_count );
sprintf(output+strlen(output), "Warmup Count : %d\n", warmup_count );

View File

@ -305,7 +305,7 @@ protected:
std::string event_prefix; // The prefix applied to event names as they are created
std::string label_format; // The format of the timestamp on the images
Coord label_coord; // The coordinates of the timestamp on the images
Vector2 label_coord; // The coordinates of the timestamp on the images
int label_size; // Size of the timestamp on the images
int32_t image_buffer_count; // Size of circular image buffer, kept in /dev/shm
int32_t max_image_buffer_count; // Max # of video packets to keep in packet queue

View File

@ -19,91 +19,103 @@
#include "zm_poly.h"
#include "zm_line.h"
#include <cmath>
void Polygon::calcArea() {
double float_area = 0.0L;
for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ ) {
double trap_area = ((coords[i].X()-coords[j].X())*((coords[i].Y()+coords[j].Y())))/2.0L;
Polygon::Polygon(std::vector<Vector2> vertices) : vertices_(std::move(vertices)), area(0) {
UpdateExtent();
UpdateArea();
UpdateCentre();
}
void Polygon::UpdateExtent() {
if (vertices_.empty())
return;
int min_x = vertices_[0].x_;
int max_x = 0;
int min_y = vertices_[0].y_;
int max_y = 0;
for (const Vector2 &vertex : vertices_) {
min_x = std::min(min_x, vertex.x_);
max_x = std::max(max_x, vertex.x_);
min_y = std::min(min_y, vertex.y_);
max_y = std::max(max_y, vertex.y_);
}
extent = Box({min_x, min_y}, {max_x, max_y});
}
void Polygon::UpdateArea() {
double float_area = 0.0;
for (size_t i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
double trap_area = ((vertices_[i].x_ - vertices_[j].x_) * ((vertices_[i].y_ + vertices_[j].y_))) / 2.0;
float_area += trap_area;
//printf( "%.2f (%.2f)\n", float_area, trap_area );
}
area = (int)round(fabs(float_area));
area = static_cast<int32>(std::lround(std::fabs(float_area)));
}
void Polygon::calcCentre() {
if ( !area && n_coords )
calcArea();
double float_x = 0.0L, float_y = 0.0L;
for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ ) {
float_x += ((coords[i].Y()-coords[j].Y())*((coords[i].X()*2)+(coords[i].X()*coords[j].X())+(coords[j].X()*2)));
float_y += ((coords[j].X()-coords[i].X())*((coords[i].Y()*2)+(coords[i].Y()*coords[j].Y())+(coords[j].Y()*2)));
void Polygon::UpdateCentre() {
if (!area && !vertices_.empty())
UpdateArea();
double float_x = 0.0;
double float_y = 0.0;
for (size_t i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
float_x += ((vertices_[i].y_ - vertices_[j].y_)
* ((vertices_[i].x_ * 2) + (vertices_[i].x_ * vertices_[j].x_) + (vertices_[j].x_ * 2)));
float_y += ((vertices_[j].x_ - vertices_[i].x_)
* ((vertices_[i].y_ * 2) + (vertices_[i].y_ * vertices_[j].y_) + (vertices_[j].y_ * 2)));
}
float_x /= (6*area);
float_y /= (6*area);
centre = Coord( (int)round(float_x), (int)round(float_y) );
float_x /= (6 * area);
float_y /= (6 * area);
centre = Vector2(static_cast<int32>(std::lround(float_x)), static_cast<int32>(std::lround(float_y)));
}
Polygon::Polygon(int p_n_coords, const Coord *p_coords) : n_coords(p_n_coords) {
coords = new Coord[n_coords];
int min_x = -1;
int max_x = -1;
int min_y = -1;
int max_y = -1;
for ( int i = 0; i < n_coords; i++ ) {
coords[i] = p_coords[i];
if ( min_x == -1 || coords[i].X() < min_x )
min_x = coords[i].X();
if ( max_x == -1 || coords[i].X() > max_x )
max_x = coords[i].X();
if ( min_y == -1 || coords[i].Y() < min_y )
min_y = coords[i].Y();
if ( max_y == -1 || coords[i].Y() > max_y )
max_y = coords[i].Y();
}
extent = Box( min_x, min_y, max_x, max_y );
calcArea();
calcCentre();
}
Polygon::Polygon(const Polygon &p_polygon) :
n_coords(p_polygon.n_coords),
extent(p_polygon.extent),
area(p_polygon.area),
centre(p_polygon.centre)
{
coords = new Coord[n_coords];
for( int i = 0; i < n_coords; i++ ) {
coords[i] = p_polygon.coords[i];
}
}
Polygon &Polygon::operator=(const Polygon &p_polygon) {
n_coords = p_polygon.n_coords;
Coord *new_coords = new Coord[n_coords];
for (int i = 0; i < n_coords; i++) {
new_coords[i] = p_polygon.coords[i];
}
delete[] coords;
coords = new_coords;
extent = p_polygon.extent;
area = p_polygon.area;
centre = p_polygon.centre;
return *this;
}
bool Polygon::isInside( const Coord &coord ) const {
bool Polygon::Contains(const Vector2 &coord) const {
bool inside = false;
for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ ) {
if ( (((coords[i].Y() <= coord.Y()) && (coord.Y() < coords[j].Y()) )
|| ((coords[j].Y() <= coord.Y()) && (coord.Y() < coords[i].Y())))
&& (coord.X() < (coords[j].X() - coords[i].X()) * (coord.Y() - coords[i].Y()) / (coords[j].Y() - coords[i].Y()) + coords[i].X()))
{
for (size_t i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
if ((((vertices_[i].y_ <= coord.y_) && (coord.y_ < vertices_[j].y_)) || ((vertices_[j].y_ <= coord.y_) && (coord.y_ < vertices_[i].y_)))
&& (coord.x_ < (vertices_[j].x_ - vertices_[i].x_) * (coord.y_ - vertices_[i].y_) / (vertices_[j].y_ - vertices_[i].y_) + vertices_[i].x_)) {
inside = !inside;
}
}
return inside;
}
// Clip the polygon to a rectangular boundary box using the Sutherland-Hodgman algorithm
void Polygon::Clip(const Box &boundary) {
std::vector<Vector2> clipped_vertices = vertices_;
for (LineSegment const &clip_edge : boundary.Edges()) {
// convert our line segment to an infinite line
Line clip_line = Line(clip_edge);
std::vector<Vector2> to_clip = clipped_vertices;
clipped_vertices.clear();
for (size_t i = 0; i < to_clip.size(); ++i) {
Vector2 vert1 = to_clip[i];
Vector2 vert2 = to_clip[(i + 1) % to_clip.size()];
bool vert1_left = clip_line.IsPointLeftOfOrColinear(vert1);
bool vert2_left = clip_line.IsPointLeftOfOrColinear(vert2);
if (vert2_left) {
if (!vert1_left) {
clipped_vertices.push_back(Line(vert1, vert2).Intersection(clip_line));
}
clipped_vertices.push_back(vert2);
} else if (vert1_left) {
clipped_vertices.push_back(Line(vert1, vert2).Intersection(clip_line));
}
}
}
vertices_ = clipped_vertices;
UpdateExtent();
UpdateArea();
UpdateCentre();
}

View File

@ -21,96 +21,53 @@
#define ZM_POLY_H
#include "zm_box.h"
#include <vector>
class Coord;
struct Edge {
int min_y;
int max_y;
double min_x;
double _1_m;
//
// Class used for storing a box, which is defined as a region
// defined by two coordinates
//
static bool CompareYX(const Edge &e1, const Edge &e2) {
if (e1.min_y == e2.min_y)
return e1.min_x < e2.min_x;
return e1.min_y < e2.min_y;
}
static bool CompareX(const Edge &e1, const Edge &e2) {
return e1.min_x < e2.min_x;
}
};
// This class represents convex or concave non-self-intersecting polygons.
class Polygon {
protected:
struct Edge {
int min_y;
int max_y;
double min_x;
double _1_m;
public:
Polygon() : area(0) {}
explicit Polygon(std::vector<Vector2> vertices);
static int CompareYX( const void *p1, const void *p2 ) {
const Edge *e1 = reinterpret_cast<const Edge *>(p1), *e2 = reinterpret_cast<const Edge *>(p2);
if ( e1->min_y == e2->min_y )
return int(e1->min_x - e2->min_x);
else
return int(e1->min_y - e2->min_y);
}
static int CompareX( const void *p1, const void *p2 ) {
const Edge *e1 = reinterpret_cast<const Edge *>(p1), *e2 = reinterpret_cast<const Edge *>(p2);
return int(e1->min_x - e2->min_x);
}
};
const std::vector<Vector2> &GetVertices() const {
return vertices_;
}
struct Slice {
int min_x;
int max_x;
int n_edges;
int *edges;
const Box &Extent() const { return extent; }
int32 Area() const { return area; }
const Vector2 &Centre() const { return centre; }
Slice() {
min_x = 0;
max_x = 0;
n_edges = 0;
edges = nullptr;
}
~Slice() {
delete edges;
}
};
bool Contains(const Vector2 &coord) const;
protected:
int n_coords;
Coord *coords;
void Clip(const Box &boundary);
private:
void UpdateExtent();
void UpdateArea();
void UpdateCentre();
private:
std::vector<Vector2> vertices_;
Box extent;
int area;
Coord centre;
protected:
void initialiseEdges();
void calcArea();
void calcCentre();
public:
inline Polygon() : n_coords(0), coords(nullptr), area(0) {
}
Polygon(int p_n_coords, const Coord *p_coords);
Polygon(const Polygon &p_polygon);
~Polygon() {
delete[] coords;
}
Polygon &operator=( const Polygon &p_polygon );
inline int getNumCoords() const { return n_coords; }
inline const Coord &getCoord( int index ) const {
return coords[index];
}
inline const Box &Extent() const { return extent; }
inline int LoX() const { return extent.LoX(); }
inline int LoX(int p_lo_x) { return extent.LoX(p_lo_x); }
inline int HiX() const { return extent.HiX(); }
inline int HiX(int p_hi_x) { return extent.HiX(p_hi_x); }
inline int LoY() const { return extent.LoY(); }
inline int LoY(int p_lo_y) { return extent.LoY(p_lo_y); }
inline int HiY() const { return extent.HiY(); }
inline int HiY(int p_hi_y) { return extent.HiY(p_hi_y); }
inline int Width() const { return extent.Width(); }
inline int Height() const { return extent.Height(); }
inline int Area() const { return area; }
inline const Coord &Centre() const {
return centre;
}
bool isInside( const Coord &coord ) const;
int32 area;
Vector2 centre;
};
#endif // ZM_POLY_H

View File

@ -204,10 +204,10 @@ Image *StreamBase::prepareImage(Image *image) {
last_crop = Box();
// Recalculate crop parameters, as %ges
int click_x = (last_crop.LoX() * 100 ) / last_act_image_width; // Initial crop offset from last image
click_x += ( x * 100 ) / last_virt_image_width;
int click_y = (last_crop.LoY() * 100 ) / last_act_image_height; // Initial crop offset from last image
click_y += ( y * 100 ) / last_virt_image_height;
int click_x = (last_crop.Lo().x_ * 100) / last_act_image_width; // Initial crop offset from last image
click_x += (x * 100) / last_virt_image_width;
int click_y = (last_crop.Lo().y_ * 100) / last_act_image_height; // Initial crop offset from last image
click_y += (y * 100) / last_virt_image_height;
Debug(3, "Got adjusted click at %d%%,%d%%", click_x, click_y);
// Convert the click locations to the current image pixels
@ -231,10 +231,10 @@ Image *StreamBase::prepareImage(Image *image) {
hi_y = act_image_height - 1;
lo_y = hi_y - (send_image_height - 1);
}
last_crop = Box( lo_x, lo_y, hi_x, hi_y );
last_crop = Box({lo_x, lo_y}, {hi_x, hi_y});
} // end if ( mag != last_mag || x != last_x || y != last_y )
Debug(3, "Cropping to %d,%d -> %d,%d", last_crop.LoX(), last_crop.LoY(), last_crop.HiX(), last_crop.HiY());
Debug(3, "Cropping to %d,%d -> %d,%d", last_crop.Lo().x_, last_crop.Lo().y_, last_crop.Hi().x_, last_crop.Hi().y_);
if ( !image_copied ) {
static Image copy_image;
copy_image.Assign(*image);

80
src/zm_vector2.h Normal file
View File

@ -0,0 +1,80 @@
//
// ZoneMinder Coordinate Class Interface, $Date$, $Revision$
// Copyright (C) 2001-2008 Philip Coombes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#ifndef ZM_VECTOR2_H
#define ZM_VECTOR2_H
#include "zm_define.h"
#include <cmath>
#include <limits>
//
// Class used for storing an x,y pair, i.e. a coordinate/vector
//
class Vector2 {
public:
Vector2() : x_(0), y_(0) {}
Vector2(int32 x, int32 y) : x_(x), y_(y) {}
static Vector2 Inf() {
static const Vector2 inf = {std::numeric_limits<int32>::max(), std::numeric_limits<int32>::max()};
return inf;
}
bool operator==(const Vector2 &rhs) const { return (x_ == rhs.x_ && y_ == rhs.y_); }
bool operator!=(const Vector2 &rhs) const { return (x_ != rhs.x_ || y_ != rhs.y_); }
// These operators are not idiomatic. If lexicographic comparison is needed, it should be implemented separately.
bool operator>(const Vector2 &rhs) const = delete;
bool operator>=(const Vector2 &rhs) const = delete;
bool operator<(const Vector2 &rhs) const = delete;
bool operator<=(const Vector2 &rhs) const = delete;
Vector2 operator+(const Vector2 &rhs) const {
return {x_ + rhs.x_, y_ + rhs.y_};
}
Vector2 operator-(const Vector2 &rhs) const {
return {x_ - rhs.x_, y_ - rhs.y_};
}
Vector2 operator*(double rhs) const {
return {static_cast<int32>(std::lround(x_ * rhs)), static_cast<int32>(std::lround(y_ * rhs))};
}
Vector2 &operator+=(const Vector2 &rhs) {
x_ += rhs.x_;
y_ += rhs.y_;
return *this;
}
Vector2 &operator-=(const Vector2 &rhs) {
x_ -= rhs.x_;
y_ -= rhs.y_;
return *this;
}
// Calculated the determinant of the 2x2 matrix as given by [[x_, y_], [v.x_y, v.y_]]
int32 Determinant(Vector2 const &v) const {
return (x_ * v.y_) - (y_ * v.x_);
}
public:
int32 x_;
int32 y_;
};
#endif // ZM_VECTOR2_H

View File

@ -23,7 +23,7 @@
#include "zm_fifo_debug.h"
#include "zm_monitor.h"
void Zone::Setup(
void Zone::Setup(
ZoneType p_type,
const Polygon &p_polygon,
const Rgb p_alarm_rgb,
@ -32,7 +32,7 @@ void Zone::Setup(
int p_max_pixel_threshold,
int p_min_alarm_pixels,
int p_max_alarm_pixels,
const Coord &p_filter_box,
const Vector2 &p_filter_box,
int p_min_filter_pixels,
int p_max_filter_pixels,
int p_min_blob_pixels,
@ -122,7 +122,7 @@ void Zone::RecordStats(const Event *event) {
"PixelDiff=%d, AlarmPixels=%d, FilterPixels=%d, BlobPixels=%d, "
"Blobs=%d, MinBlobSize=%d, MaxBlobSize=%d, "
"MinX=%d, MinY=%d, MaxX=%d, MaxY=%d, Score=%d",
monitor->Id(), id, event->Id(), event->Frames(),
monitor->Id(), id, event->Id(), event->Frames(),
stats.pixel_diff_,
stats.alarm_pixels_,
stats.alarm_filter_pixels_,
@ -130,10 +130,10 @@ void Zone::RecordStats(const Event *event) {
stats.alarm_blobs_,
stats.min_blob_size_,
stats.max_blob_size_,
stats.alarm_box_.LoX(),
stats.alarm_box_.LoY(),
stats.alarm_box_.HiX(),
stats.alarm_box_.HiY(),
stats.alarm_box_.Lo().x_,
stats.alarm_box_.Lo().y_,
stats.alarm_box_.Hi().x_,
stats.alarm_box_.Hi().y_,
stats.score_
);
zmDbDo(sql);
@ -219,10 +219,10 @@ bool Zone::CheckAlarms(const Image *delta_image) {
int alarm_mid_x = -1;
int alarm_mid_y = -1;
unsigned int lo_y = polygon.LoY();
unsigned int lo_x = polygon.LoX();
unsigned int hi_x = polygon.HiX();
unsigned int hi_y = polygon.HiY();
unsigned int lo_x = polygon.Extent().Lo().x_;
unsigned int lo_y = polygon.Extent().Lo().y_;
unsigned int hi_x = polygon.Extent().Hi().x_;
unsigned int hi_y = polygon.Extent().Hi().y_;
Debug(4, "Checking alarms for zone %d/%s in lines %d -> %d", id, label.c_str(), lo_y, hi_y);
@ -267,8 +267,8 @@ bool Zone::CheckAlarms(const Image *delta_image) {
Debug(5, "Current score is %d", stats.score_);
if (check_method >= FILTERED_PIXELS) {
int bx = filter_box.X();
int by = filter_box.Y();
int bx = filter_box.x_;
int by = filter_box.y_;
int bx1 = bx-1;
int by1 = by-1;
@ -620,20 +620,20 @@ bool Zone::CheckAlarms(const Image *delta_image) {
stats.score_ = 0;
return false;
}
if (max_blob_pixels != 0)
stats.score_ = (100*stats.alarm_blob_pixels_)/max_blob_pixels;
else
else
stats.score_ = (100*stats.alarm_blob_pixels_)/polygon.Area();
if (stats.score_ < 1)
stats.score_ = 1; /* Fix for score of 0 when frame meets thresholds but alarmed area is not big enough */
Debug(5, "Current score is %d", stats.score_);
alarm_lo_x = polygon.HiX()+1;
alarm_hi_x = polygon.LoX()-1;
alarm_lo_y = polygon.HiY()+1;
alarm_hi_y = polygon.LoY()-1;
alarm_lo_x = polygon.Extent().Hi().x_ + 1;
alarm_hi_x = polygon.Extent().Lo().x_ - 1;
alarm_lo_y = polygon.Extent().Hi().y_ + 1;
alarm_hi_y = polygon.Extent().Lo().y_ - 1;
for (uint32 i = 1; i < kWhite; i++) {
BlobStats *bs = &blob_stats[i];
@ -684,11 +684,11 @@ bool Zone::CheckAlarms(const Image *delta_image) {
// Now outline the changed region
if (stats.score_) {
stats.alarm_box_ = Box(Coord(alarm_lo_x, alarm_lo_y), Coord(alarm_hi_x, alarm_hi_y));
stats.alarm_box_ = Box(Vector2(alarm_lo_x, alarm_lo_y), Vector2(alarm_hi_x, alarm_hi_y));
//if ( monitor->followMotion() )
if ( true ) {
stats.alarm_centre_ = Coord(alarm_mid_x, alarm_mid_y);
stats.alarm_centre_ = Vector2(alarm_mid_x, alarm_mid_y);
} else {
stats.alarm_centre_ = stats.alarm_box_.Centre();
}
@ -748,37 +748,39 @@ bool Zone::CheckAlarms(const Image *delta_image) {
bool Zone::ParsePolygonString(const char *poly_string, Polygon &polygon) {
char *str = (char *)poly_string;
int n_coords = 0;
int max_n_coords = strlen(str)/4;
Coord *coords = new Coord[max_n_coords];
std::vector<Vector2> vertices;
vertices.reserve(max_n_coords);
while (*str != '\0') {
char *cp = strchr(str, ',');
if (!cp) {
Error("Bogus coordinate %s found in polygon string", str);
break;
}
}
int x = atoi(str);
int y = atoi(cp+1);
int y = atoi(cp + 1);
Debug(3, "Got coordinate %d,%d from polygon string", x, y);
coords[n_coords++] = Coord(x, y);
vertices.emplace_back(x, y);
char *ws = strchr(cp+2, ' ');
if (ws)
str = ws+1;
else
char *ws = strchr(cp + 2, ' ');
if (ws) {
str = ws + 1;
} else {
break;
} // end while ! end of string
if (n_coords > 2) {
Debug(3, "Successfully parsed polygon string %s", str);
polygon = Polygon(n_coords, coords);
} else {
Error("Not enough coordinates to form a polygon!");
n_coords = 0;
}
}
delete[] coords;
return n_coords ? true : false;
if (vertices.size() > 2) {
Debug(3, "Successfully parsed polygon string %s", str);
polygon = Polygon(vertices);
} else {
Error("Not enough coordinates to form a polygon!");
}
return !vertices.empty();
} // end bool Zone::ParsePolygonString(const char *poly_string, Polygon &polygon)
bool Zone::ParseZoneString(const char *zone_string, int &zone_id, int &colour, Polygon &polygon) {
@ -872,14 +874,21 @@ std::vector<Zone> Zone::Load(Monitor *monitor) {
continue;
}
if ( polygon.LoX() < 0 || polygon.HiX() >= (int)monitor->Width()
|| polygon.LoY() < 0 || polygon.HiY() >= (int)monitor->Height() ) {
if (polygon.Extent().Lo().x_ < 0 || polygon.Extent().Hi().x_ > static_cast<int32>(monitor->Width())
|| polygon.Extent().Lo().y_ < 0 || polygon.Extent().Hi().y_ > static_cast<int32>(monitor->Height())) {
Error("Zone %d/%s for monitor %s extends outside of image dimensions, (%d,%d), (%d,%d), fixing",
Id, Name, monitor->Name(), polygon.LoX(), polygon.LoY(), polygon.HiX(), polygon.HiY());
if ( polygon.LoX() < 0 ) polygon.LoX(0);
if ( polygon.HiX() >= (int)monitor->Width()) polygon.HiX((int)monitor->Width());
if ( polygon.LoY() < 0 ) polygon.LoY(0);
if ( polygon.HiY() >= (int)monitor->Height() ) polygon.HiY((int)monitor->Height());
Id,
Name,
monitor->Name(),
polygon.Extent().Lo().x_,
polygon.Extent().Lo().y_,
polygon.Extent().Hi().x_,
polygon.Extent().Hi().y_);
polygon.Clip(Box(
{0, 0},
{static_cast<int32>(monitor->Width()), static_cast<int32>(monitor->Height())}
));
}
if ( false && !strcmp( Units, "Percent" ) ) {
@ -899,7 +908,7 @@ std::vector<Zone> Zone::Load(Monitor *monitor) {
zones.emplace_back(
monitor, Id, Name, Type, polygon, AlarmRGB,
CheckMethod, MinPixelThreshold, MaxPixelThreshold,
MinAlarmPixels, MaxAlarmPixels, Coord(FilterX, FilterY),
MinAlarmPixels, MaxAlarmPixels, Vector2(FilterX, FilterY),
MinFilterPixels, MaxFilterPixels,
MinBlobPixels, MaxBlobPixels, MinBlobs, MaxBlobs,
OverloadFrames, ExtendAlarmFrames);
@ -922,9 +931,9 @@ bool Zone::DumpSettings(char *output, bool /*verbose*/) const {
type==INACTIVE?"Inactive":(
type==PRIVACY?"Privacy":"Unknown"
))))));
sprintf( output+strlen(output), " Shape : %d points\n", polygon.getNumCoords() );
for ( int i = 0; i < polygon.getNumCoords(); i++ ) {
sprintf( output+strlen(output), " %i: %d,%d\n", i, polygon.getCoord( i ).X(), polygon.getCoord( i ).Y() );
sprintf( output+strlen(output), " Shape : %zu points\n", polygon.GetVertices().size() );
for (size_t i = 0; i < polygon.GetVertices().size(); i++) {
sprintf(output + strlen(output), " %zu: %d,%d\n", i, polygon.GetVertices()[i].x_, polygon.GetVertices()[i].y_);
}
sprintf( output+strlen(output), " Alarm RGB : %06x\n", alarm_rgb );
sprintf( output+strlen(output), " Check Method: %d - %s\n", check_method,
@ -936,7 +945,7 @@ bool Zone::DumpSettings(char *output, bool /*verbose*/) const {
sprintf( output+strlen(output), " Max Pixel Threshold : %d\n", max_pixel_threshold );
sprintf( output+strlen(output), " Min Alarm Pixels : %d\n", min_alarm_pixels );
sprintf( output+strlen(output), " Max Alarm Pixels : %d\n", max_alarm_pixels );
sprintf( output+strlen(output), " Filter Box : %d,%d\n", filter_box.X(), filter_box.Y() );
sprintf(output+strlen(output), " Filter Box : %d,%d\n", filter_box.x_, filter_box.y_ );
sprintf( output+strlen(output), " Min Filter Pixels : %d\n", min_filter_pixels );
sprintf( output+strlen(output), " Max Filter Pixels : %d\n", max_filter_pixels );
sprintf( output+strlen(output), " Min Blob Pixels : %d\n", min_blob_pixels );
@ -960,8 +969,8 @@ void Zone::std_alarmedpixels(
if ( max_pixel_threshold )
calc_max_pixel_threshold = max_pixel_threshold;
lo_y = polygon.LoY();
hi_y = polygon.HiY();
lo_y = polygon.Extent().Lo().y_;
hi_y = polygon.Extent().Hi().y_;
for ( unsigned int y = lo_y; y <= hi_y; y++ ) {
unsigned int lo_x = ranges[y].lo_x;
unsigned int hi_x = ranges[y].hi_x;

View File

@ -21,12 +21,12 @@
#define ZM_ZONE_H
#include "zm_box.h"
#include "zm_coord.h"
#include "zm_define.h"
#include "zm_config.h"
#include "zm_poly.h"
#include "zm_rgb.h"
#include "zm_zone_stats.h"
#include "zm_vector2.h"
#include <algorithm>
#include <string>
@ -77,7 +77,7 @@ class Zone {
int min_alarm_pixels;
int max_alarm_pixels;
Coord filter_box;
Vector2 filter_box;
int min_filter_pixels;
int max_filter_pixels;
@ -112,7 +112,7 @@ class Zone {
int p_max_pixel_threshold,
int p_min_alarm_pixels,
int p_max_alarm_pixels,
const Coord &p_filter_box,
const Vector2 &p_filter_box,
int p_min_filter_pixels,
int p_max_filter_pixels,
int p_min_blob_pixels,
@ -137,7 +137,7 @@ class Zone {
int p_max_pixel_threshold=0,
int p_min_alarm_pixels=50,
int p_max_alarm_pixels=75000,
const Coord &p_filter_box=Coord( 3, 3 ),
const Vector2 &p_filter_box = Vector2(3, 3),
int p_min_filter_pixels=50,
int p_max_filter_pixels=50000,
int p_min_blob_pixels=10,
@ -164,7 +164,7 @@ class Zone {
blob_stats{},
stats(p_id)
{
Setup(Zone::INACTIVE, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Coord(0, 0), 0, 0, 0, 0, 0, 0, 0, 0);
Setup(Zone::INACTIVE, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Vector2(0, 0), 0, 0, 0, 0, 0, 0, 0, 0);
}
Zone(Monitor *p_monitor, int p_id, const char *p_label, ZoneType p_type, const Polygon &p_polygon)
:
@ -174,7 +174,7 @@ class Zone {
blob_stats{},
stats(p_id)
{
Setup(p_type, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Coord( 0, 0 ), 0, 0, 0, 0, 0, 0, 0, 0 );
Setup(p_type, p_polygon, kRGBBlack, (Zone::CheckMethod)0, 0, 0, 0, 0, Vector2(0, 0), 0, 0, 0, 0, 0, 0, 0, 0 );
}
Zone(const Zone &z);
@ -195,7 +195,7 @@ class Zone {
inline bool WasAlarmed() const { return was_alarmed; }
inline void SetAlarm() { was_alarmed = alarmed; alarmed = true; }
inline void ClearAlarm() { was_alarmed = alarmed; alarmed = false; }
inline Coord GetAlarmCentre() const { return stats.alarm_centre_; }
inline Vector2 GetAlarmCentre() const { return stats.alarm_centre_; }
inline unsigned int Score() const { return stats.score_; }
inline void ResetStats() {

View File

@ -21,8 +21,8 @@
#define ZM_ZONE_STATS_H
#include "zm_box.h"
#include "zm_coord.h"
#include "zm_logger.h"
#include "zm_vector2.h"
class ZoneStats {
public:
@ -35,8 +35,6 @@ class ZoneStats {
alarm_blobs_(0),
min_blob_size_(0),
max_blob_size_(0),
alarm_box_({}),
alarm_centre_({}),
score_(0) {};
void Reset() {
@ -47,10 +45,7 @@ class ZoneStats {
alarm_blobs_ = 0;
min_blob_size_ = 0;
max_blob_size_ = 0;
alarm_box_.LoX(0);
alarm_box_.LoY(0);
alarm_box_.HiX(0);
alarm_box_.HiY(0);
alarm_box_ = {};
alarm_centre_ = {};
score_ = 0;
}
@ -67,12 +62,12 @@ class ZoneStats {
alarm_blobs_,
min_blob_size_,
max_blob_size_,
alarm_box_.LoX(),
alarm_box_.LoY(),
alarm_box_.HiX(),
alarm_box_.HiY(),
alarm_centre_.X(),
alarm_centre_.Y(),
alarm_box_.Lo().x_,
alarm_box_.Lo().y_,
alarm_box_.Hi().x_,
alarm_box_.Hi().y_,
alarm_centre_.x_,
alarm_centre_.y_,
score_
);
}
@ -87,7 +82,7 @@ class ZoneStats {
int min_blob_size_;
int max_blob_size_;
Box alarm_box_;
Coord alarm_centre_;
Vector2 alarm_centre_;
unsigned int score_;
};

View File

@ -12,10 +12,13 @@
include(Catch)
set(TEST_SOURCES
zm_box.cpp
zm_comms.cpp
zm_crypt.cpp
zm_font.cpp
zm_utils.cpp)
zm_poly.cpp
zm_utils.cpp
zm_vector2.cpp)
add_executable(tests main.cpp ${TEST_SOURCES})

52
tests/zm_box.cpp Normal file
View File

@ -0,0 +1,52 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_box.h"
TEST_CASE("Box: default constructor") {
Box b;
REQUIRE(b.Lo() == Vector2(0, 0));
REQUIRE(b.Hi() == Vector2(0, 0));
REQUIRE(b.Size() == Vector2(0, 0));
REQUIRE(b.Area() == 0);
}
TEST_CASE("Box: construct from lo and hi") {
Box b({1, 1}, {5, 5});
SECTION("basic properties") {
REQUIRE(b.Lo() == Vector2(1, 1));
REQUIRE(b.Hi() == Vector2(5, 5));
REQUIRE(b.Size() == Vector2(4 ,4));
REQUIRE(b.Area() == 16);
REQUIRE(b.Centre() == Vector2(3, 3));
REQUIRE(b.Vertices() == std::vector<Vector2>{{1, 1}, {5, 1}, {5, 5}, {1, 5}});
}
SECTION("contains") {
REQUIRE(b.Contains({0, 0}) == false);
REQUIRE(b.Contains({1, 1}) == true);
REQUIRE(b.Contains({3, 3}) == true);
REQUIRE(b.Contains({5, 5}) == true);
REQUIRE(b.Contains({6, 6}) == false);
}
}

30
tests/zm_catch2.h Normal file
View File

@ -0,0 +1,30 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ZONEMINDER_TESTS_ZM_CATCH2_H_
#define ZONEMINDER_TESTS_ZM_CATCH2_H_
#include "catch2/catch.hpp"
#include "zm_vector2.h"
inline std::ostream &operator<<(std::ostream &os, Vector2 const &value) {
os << "{ X: " << value.x_ << ", Y: " << value.y_ << " }";
return os;
}
#endif //ZONEMINDER_TESTS_ZM_CATCH2_H_

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "catch2/catch.hpp"
#include "zm_catch2.h"
#include "zm_comms.h"
#include <array>

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "catch2/catch.hpp"
#include "zm_catch2.h"
#include "zm_crypt.h"

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "catch2/catch.hpp"
#include "zm_catch2.h"
#include "zm_font.h"

71
tests/zm_poly.cpp Normal file
View File

@ -0,0 +1,71 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_poly.h"
TEST_CASE("Polygon: default constructor") {
Polygon p;
REQUIRE(p.Area() == 0);
REQUIRE(p.Centre() == Vector2(0, 0));
}
TEST_CASE("Polygon: construct from vertices") {
std::vector<Vector2> vertices{{{0, 0}, {6, 0}, {0, 6}}};
Polygon p(vertices);
REQUIRE(p.Area() == 18);
REQUIRE(p.Extent().Size() == Vector2(6, 6));
}
TEST_CASE("Polygon: clipping") {
// This a concave polygon in a shape resembling a "W"
std::vector<Vector2> v = {
{3, 1},
{5, 1},
{6, 3},
{7, 1},
{9, 1},
{10, 8},
{8, 8},
{7, 5},
{5, 5},
{4, 8},
{2, 8}
};
Polygon p(v);
REQUIRE(p.GetVertices().size() == 11);
REQUIRE(p.Extent().Size() == Vector2(8, 7));
SECTION("boundary box larger than polygon") {
p.Clip(Box({1, 0}, {11, 9}));
REQUIRE(p.GetVertices().size() == 11);
REQUIRE(p.Extent().Size() == Vector2(8, 7));
}
SECTION("boundary box smaller than polygon") {
p.Clip(Box({2, 4}, {10, 7}));
REQUIRE(p.GetVertices().size() == 8);
REQUIRE(p.Extent().Size() == Vector2(8, 3));
}
}

View File

@ -15,7 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "catch2/catch.hpp"
#include "zm_catch2.h"
#include "zm_utils.h"
#include <sstream>

94
tests/zm_vector2.cpp Normal file
View File

@ -0,0 +1,94 @@
/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_vector2.h"
TEST_CASE("Vector2: default constructor") {
Vector2 c;
REQUIRE(c.x_ == 0);
REQUIRE(c.y_ == 0);
}
TEST_CASE("Vector2: x/y constructor") {
Vector2 c(1, 2);
REQUIRE(c.x_ == 1);
REQUIRE(c.y_ == 2);
}
TEST_CASE("Vector2: assignment/copy") {
Vector2 c;
Vector2 c2(1, 2);
REQUIRE(c.x_ == 0);
REQUIRE(c.y_ == 0);
SECTION("assignment operator") {
c = c2;
REQUIRE(c.x_ == 1);
REQUIRE(c.y_ == 2);
}
SECTION("copy constructor") {
Vector2 c3(c2); // NOLINT(performance-unnecessary-copy-initialization)
REQUIRE(c3.x_ == 1);
REQUIRE(c3.y_ == 2);
}
}
TEST_CASE("Vector2: comparison operators") {
Vector2 c1(1, 2);
Vector2 c2(1, 2);
Vector2 c3(1, 3);
REQUIRE((c1 == c2) == true);
REQUIRE((c1 != c3) == true);
}
TEST_CASE("Vector2: arithmetic operators") {
Vector2 c(1, 1);
SECTION("addition") {
Vector2 c1 = c + Vector2(1, 1);
REQUIRE(c1 == Vector2(2, 2));
c += {1, 2};
REQUIRE(c == Vector2(2, 3));
}
SECTION("subtraction") {
Vector2 c1 = c - Vector2(1, 1);
REQUIRE(c1 == Vector2(0, 0));
c -= {1, 2};
REQUIRE(c == Vector2(0, -1));
}
SECTION("scalar multiplication") {
c = c * 2;
REQUIRE(c == Vector2(2, 2));
}
}
TEST_CASE("Vector2: determinate") {
Vector2 v(1, 1);
REQUIRE(v.Determinant({0, 0}) == 0);
REQUIRE(v.Determinant({1, 1}) == 0);
REQUIRE(v.Determinant({1, 2}) == 1);
}