/** * \brief Draws this surface on another surface. * \param dst_surface The destination surface. * \param dst_position Coordinates on the destination surface. */ void Surface::raw_draw(Surface& dst_surface, const Point& dst_position) { Rectangle region(0, 0, width, height); raw_draw_region(region, dst_surface, dst_position); }
void KeyboardLayoutView::_DrawKey(BView* view, BRect updateRect, const Key* key, BRect rect, bool pressed) { rgb_color base = key->dark ? kDarkColor : kBrightColor; rgb_color background = ui_color(B_PANEL_BACKGROUND_COLOR); key_kind keyKind = kNormalKey; int32 deadKey = 0; bool secondDeadKey = false; bool isDeadKeyEnabled = true; char text[32]; if (fKeymap != NULL) { _GetKeyLabel(key, text, sizeof(text), keyKind); deadKey = fKeymap->DeadKey(key->code, fModifiers, &isDeadKeyEnabled); secondDeadKey = fKeymap->IsDeadSecondKey(key->code, fModifiers, fDeadKey); } else { // Show the key code if there is no keymap snprintf(text, sizeof(text), "%02" B_PRIx32, key->code); } _SetFontSize(view, keyKind); if (secondDeadKey) base = kSecondDeadKeyColor; else if (deadKey > 0 && isDeadKeyEnabled) base = kDeadKeyColor; if (key->shape == kRectangleKeyShape) { _DrawKeyButton(view, rect, updateRect, base, background, pressed); rect.InsetBy(1, 1); _GetAbbreviatedKeyLabelIfNeeded(view, rect, key, text, sizeof(text)); be_control_look->DrawLabel(view, text, rect, updateRect, base, 0, BAlignment(B_ALIGN_CENTER, B_ALIGN_MIDDLE)); } else if (key->shape == kEnterKeyShape) { BRect topLeft = rect; BRect topRight = rect; BRect bottomLeft = rect; BRect bottomRight = rect; // TODO: for some reason, this does not always equal the bottom of // the other keys... bottomLeft.top = floorf(rect.top + fLayout->DefaultKeySize().height * fFactor - fGap - 1); bottomLeft.right = floorf(rect.left + (key->frame.Width() - key->second_row) * fFactor - fGap - 2); topLeft.bottom = bottomLeft.top; topLeft.right = bottomLeft.right + 1; // add one to make the borders meet topRight.bottom = topLeft.bottom; topRight.left = topLeft.right; bottomRight.top = bottomLeft.top; bottomRight.left = bottomLeft.right; // draw top left corner be_control_look->DrawButtonFrame(view, topLeft, updateRect, 4.0f, 0.0f, 4.0f, 0.0f, base, background, pressed ? BControlLook::B_ACTIVATED : 0, BControlLook::B_LEFT_BORDER | BControlLook::B_TOP_BORDER | BControlLook::B_BOTTOM_BORDER); be_control_look->DrawButtonBackground(view, topLeft, updateRect, 4.0f, 0.0f, 4.0f, 0.0f, base, pressed ? BControlLook::B_ACTIVATED : 0, BControlLook::B_LEFT_BORDER | BControlLook::B_TOP_BORDER | BControlLook::B_BOTTOM_BORDER); // draw top right corner be_control_look->DrawButtonFrame(view, topRight, updateRect, 0.0f, 4.0f, 0.0f, 0.0f, base, background, pressed ? BControlLook::B_ACTIVATED : 0, BControlLook::B_TOP_BORDER | BControlLook::B_RIGHT_BORDER); be_control_look->DrawButtonBackground(view, topRight, updateRect, 0.0f, 4.0f, 0.0f, 0.0f, base, pressed ? BControlLook::B_ACTIVATED : 0, BControlLook::B_TOP_BORDER | BControlLook::B_RIGHT_BORDER); // draw bottom right corner be_control_look->DrawButtonFrame(view, bottomRight, updateRect, 0.0f, 0.0f, 4.0f, 4.0f, base, background, pressed ? BControlLook::B_ACTIVATED : 0, BControlLook::B_LEFT_BORDER | BControlLook::B_RIGHT_BORDER | BControlLook::B_BOTTOM_BORDER); be_control_look->DrawButtonBackground(view, bottomRight, updateRect, 0.0f, 0.0f, 4.0f, 4.0f, base, pressed ? BControlLook::B_ACTIVATED : 0, BControlLook::B_LEFT_BORDER | BControlLook::B_RIGHT_BORDER | BControlLook::B_BOTTOM_BORDER); // clip out the bottom left corner bottomLeft.right += 1; bottomLeft.top -= 2; BRegion region(rect); region.Exclude(bottomLeft); view->ConstrainClippingRegion(®ion); // Fill in the rect with the background color SetHighColor(background); FillRect(rect); // draw the button background BRect bgRect = rect.InsetByCopy(2, 2); be_control_look->DrawButtonBackground(view, bgRect, updateRect, 4.0f, 4.0f, 0.0f, 4.0f, base, pressed ? BControlLook::B_ACTIVATED : 0); rect.left = bottomLeft.right; _GetAbbreviatedKeyLabelIfNeeded(view, rect, key, text, sizeof(text)); // draw the button label be_control_look->DrawLabel(view, text, rect, updateRect, base, 0, BAlignment(B_ALIGN_CENTER, B_ALIGN_MIDDLE)); // reset the clipping region view->ConstrainClippingRegion(NULL); } }
// Print a RegionGraphNode void RegionGraphNode::_print(std::ostream& os, const GraphGC& gc) const { cleanRegion(os, gc, region(gc)); }
QRegion ImageUI::region() const { QRect region( preview.rect() ); region.translate( preview_position.x(), preview_position.y() ); return region; }
void ContentHostBase::Composite(EffectChain& aEffectChain, float aOpacity, const gfx::Matrix4x4& aTransform, const Filter& aFilter, const Rect& aClipRect, const nsIntRegion* aVisibleRegion, TiledLayerProperties* aLayerProperties) { NS_ASSERTION(aVisibleRegion, "Requires a visible region"); AutoLockTextureHost lock(mTextureHost); AutoLockTextureHost lockOnWhite(mTextureHostOnWhite); if (!mTextureHost || !lock.IsValid() || !lockOnWhite.IsValid()) { return; } RefPtr<NewTextureSource> source = mTextureHost->GetTextureSources(); RefPtr<NewTextureSource> sourceOnWhite = mTextureHostOnWhite ? mTextureHostOnWhite->GetTextureSources() : nullptr; if (!source) { return; } RefPtr<TexturedEffect> effect = CreateTexturedEffect(source, sourceOnWhite, aFilter); aEffectChain.mPrimaryEffect = effect; nsIntRegion tmpRegion; const nsIntRegion* renderRegion; if (PaintWillResample()) { // If we're resampling, then the texture image will contain exactly the // entire visible region's bounds, and we should draw it all in one quad // to avoid unexpected aliasing. tmpRegion = aVisibleRegion->GetBounds(); renderRegion = &tmpRegion; } else { renderRegion = aVisibleRegion; } nsIntRegion region(*renderRegion); nsIntPoint origin = GetOriginOffset(); // translate into TexImage space, buffer origin might not be at texture (0,0) region.MoveBy(-origin); // Figure out the intersecting draw region gfx::IntSize texSize = source->GetSize(); nsIntRect textureRect = nsIntRect(0, 0, texSize.width, texSize.height); textureRect.MoveBy(region.GetBounds().TopLeft()); nsIntRegion subregion; subregion.And(region, textureRect); if (subregion.IsEmpty()) { // Region is empty, nothing to draw return; } nsIntRegion screenRects; nsIntRegion regionRects; // Collect texture/screen coordinates for drawing nsIntRegionRectIterator iter(subregion); while (const nsIntRect* iterRect = iter.Next()) { nsIntRect regionRect = *iterRect; nsIntRect screenRect = regionRect; screenRect.MoveBy(origin); screenRects.Or(screenRects, screenRect); regionRects.Or(regionRects, regionRect); } TileIterator* tileIter = source->AsTileIterator(); TileIterator* iterOnWhite = nullptr; if (tileIter) { tileIter->BeginTileIteration(); } if (mTextureHostOnWhite) { iterOnWhite = sourceOnWhite->AsTileIterator(); MOZ_ASSERT(!tileIter || tileIter->GetTileCount() == iterOnWhite->GetTileCount(), "Tile count mismatch on component alpha texture"); if (iterOnWhite) { iterOnWhite->BeginTileIteration(); } } bool usingTiles = (tileIter && tileIter->GetTileCount() > 1); do { if (iterOnWhite) { MOZ_ASSERT(iterOnWhite->GetTileRect() == tileIter->GetTileRect(), "component alpha textures should be the same size."); } nsIntRect texRect = tileIter ? tileIter->GetTileRect() : nsIntRect(0, 0, texSize.width, texSize.height); // Draw texture. If we're using tiles, we do repeating manually, as texture // repeat would cause each individual tile to repeat instead of the // compound texture as a whole. This involves drawing at most 4 sections, // 2 for each axis that has texture repeat. for (int y = 0; y < (usingTiles ? 2 : 1); y++) { for (int x = 0; x < (usingTiles ? 2 : 1); x++) { nsIntRect currentTileRect(texRect); currentTileRect.MoveBy(x * texSize.width, y * texSize.height); nsIntRegionRectIterator screenIter(screenRects); nsIntRegionRectIterator regionIter(regionRects); const nsIntRect* screenRect; const nsIntRect* regionRect; while ((screenRect = screenIter.Next()) && (regionRect = regionIter.Next())) { nsIntRect tileScreenRect(*screenRect); nsIntRect tileRegionRect(*regionRect); // When we're using tiles, find the intersection between the tile // rect and this region rect. Tiling is then handled by the // outer for-loops and modifying the tile rect. if (usingTiles) { tileScreenRect.MoveBy(-origin); tileScreenRect = tileScreenRect.Intersect(currentTileRect); tileScreenRect.MoveBy(origin); if (tileScreenRect.IsEmpty()) continue; tileRegionRect = regionRect->Intersect(currentTileRect); tileRegionRect.MoveBy(-currentTileRect.TopLeft()); } gfx::Rect rect(tileScreenRect.x, tileScreenRect.y, tileScreenRect.width, tileScreenRect.height); effect->mTextureCoords = Rect(Float(tileRegionRect.x) / texRect.width, Float(tileRegionRect.y) / texRect.height, Float(tileRegionRect.width) / texRect.width, Float(tileRegionRect.height) / texRect.height); GetCompositor()->DrawQuad(rect, aClipRect, aEffectChain, aOpacity, aTransform); if (usingTiles) { DiagnosticTypes diagnostics = DIAGNOSTIC_CONTENT | DIAGNOSTIC_BIGIMAGE; diagnostics |= iterOnWhite ? DIAGNOSTIC_COMPONENT_ALPHA : 0; GetCompositor()->DrawDiagnostics(diagnostics, rect, aClipRect, aTransform); } } } } if (iterOnWhite) { iterOnWhite->NextTile(); } } while (usingTiles && tileIter->NextTile()); if (tileIter) { tileIter->EndTileIteration(); } if (iterOnWhite) { iterOnWhite->EndTileIteration(); } DiagnosticTypes diagnostics = DIAGNOSTIC_CONTENT; diagnostics |= iterOnWhite ? DIAGNOSTIC_COMPONENT_ALPHA : 0; GetCompositor()->DrawDiagnostics(diagnostics, *aVisibleRegion, aClipRect, aTransform); }
TEST_F(TestRegionNoArgs,BasicRegion_ShallowHistory_Resume2) { typedef TestConcurrentCompositeStateNoArgsMock < TestStateMachineNoEventArgsMock > ConcurrentCompositeStateMockType; typedef TestRegionNoArgsMock < ConcurrentCompositeStateMockType , sttcl::CompositeStateHistoryType::Shallow > RegionMockType; typedef TestRegionInnerStateNoArgsMock<ConcurrentCompositeStateMockType,RegionMockType> RegionInnerStateMockType; ::testing::NiceMock<TestStateMachineNoEventArgsMock> stateMachine("stateMachine"); ::testing::NiceMock < ConcurrentCompositeStateMockType > compositeState(&stateMachine); ::testing::NiceMock < RegionMockType > region(&compositeState,"region"); ::testing::NiceMock < RegionInnerStateMockType > innerState1("innerState1"); ::testing::NiceMock < RegionInnerStateMockType > innerState2("innerState1"); ::testing::NiceMock < TestSimpleStateNoArgsMock<TestStateMachineNoEventArgsMock> > outerState("outerState"); stateMachine.autoFinalize(false); compositeState.setRegion(0,®ion); region.initialState(&innerState1); stateMachine.initialState(&compositeState); // Setup mock call expectations //---------------------------------------------------------------------------- EXPECT_CALL(compositeState,handleEvent1(&stateMachine)) .Times(1); EXPECT_CALL(compositeState,handleEvent2(&stateMachine)) .Times(1) .WillOnce( TRIGGER_STATE_CHANGE(ConcurrentCompositeStateMockType, handleEvent2, &compositeState, &outerState) ); EXPECT_CALL(compositeState,endDoImpl(&stateMachine)) .Times(2); EXPECT_CALL(compositeState,exitImpl(&stateMachine)) .Times(2); // Check region calls EXPECT_CALL(region,enterRegionImpl(&compositeState)) .Times(2); EXPECT_CALL(region,startingRegionThread()) .Times(2); EXPECT_CALL(region,initializeImpl(_)) .Times(2); // TODO: Eliminiate (superflous?) calls to finalize(Impl) EXPECT_CALL(region,finalizeImpl(_)) .Times(3); EXPECT_CALL(region,endingRegionThread()) .Times(2); EXPECT_CALL(region,exitRegionImpl(&compositeState)) .Times(2); EXPECT_CALL(outerState,entryImpl(&stateMachine)) .Times(1); EXPECT_CALL(outerState,startDoImpl(&stateMachine)) .Times(1); EXPECT_CALL(outerState,handleEvent3(&stateMachine)) .Times(1) .WillOnce( TRIGGER_STATE_CHANGE(TestSimpleStateNoArgsMock<TestStateMachineNoEventArgsMock>, handleEvent3, &outerState, &compositeState) ); EXPECT_CALL(outerState,endDoImpl(&stateMachine)) .Times(1); EXPECT_CALL(outerState,exitImpl(&stateMachine)) .Times(1); EXPECT_CALL(innerState1,entryImpl(®ion)) .Times(1); EXPECT_CALL(innerState1,startDoImpl(®ion)) .Times(1); // TODO: Eliminiate (superflous?) calls to initSubStateMachinesImpl EXPECT_CALL(innerState1,initSubStateMachinesImpl(true)) .Times(2); // EXPECT_CALL(innerState1,initSubStateMachinesImpl(true)) // .Times(1); EXPECT_CALL(innerState1,handleEvent1(&compositeState,®ion)) .Times(1) .WillOnce( TRIGGER_STATE_CHANGE2(RegionInnerStateMockType, handleEvent1, &innerState1, &innerState2) ); EXPECT_CALL(innerState1,endDoImpl(®ion)) .Times(1); EXPECT_CALL(innerState1,exitImpl(®ion)) .Times(1); EXPECT_CALL(innerState2,entryImpl(®ion)) .Times(1); EXPECT_CALL(innerState2,startDoImpl(®ion)) .Times(1); // EXPECT_CALL(innerState2,initSubStateMachinesImpl(true)) // .Times(1); EXPECT_CALL(innerState2,endDoImpl(®ion)) .Times(2); EXPECT_CALL(innerState2,exitImpl(®ion)) .Times(2); // Run the state machine //---------------------------------------------------------------------------- // STTCL_TEST_LOG_ALL(); stateMachine.initialize(true); // Give the region thread(s) a chance to run sttcl::internal::SttclThread<>::sleep(sttcl::TimeDuration<>(0,0,0,100)); stateMachine.triggerEvent1(); // Give the region thread(s) a chance to run sttcl::internal::SttclThread<>::sleep(sttcl::TimeDuration<>(0,0,0,100)); stateMachine.triggerEvent2(); // Give the region thread(s) a chance to run sttcl::internal::SttclThread<>::sleep(sttcl::TimeDuration<>(0,0,0,100)); stateMachine.triggerEvent3(); // Give the region thread(s) a chance to run sttcl::internal::SttclThread<>::sleep(sttcl::TimeDuration<>(0,0,0,100)); stateMachine.finalize(true); // STTCL_TEST_LOG_END(); }
bool QDecorationStyled::paint(QPainter *painter, const QWidget *widget, int decorationRegion, DecorationState state) { if (decorationRegion == None) return false; bool isActive = (widget == qApp->activeWindow()); QPalette pal = qApp->palette(); //ideally, the difference between Active and Inactive should be enough, so we shouldn't need to test this if (!isActive) { //pal.setCurrentColorGroup(QPalette::Disabled); //Can't do this either, because of palette limitations //copied from Q3TitleBar: pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Inactive, QPalette::Dark)); pal.setColor(QPalette::Inactive, QPalette::Base, pal.color(QPalette::Inactive, QPalette::Dark)); pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Inactive, QPalette::Window)); } Qt::WindowFlags flags = widget->windowFlags(); bool hasBorder = !widget->isMaximized(); bool hasTitle = flags & Qt::WindowTitleHint; bool hasSysMenu = flags & Qt::WindowSystemMenuHint; bool hasContextHelp = flags & Qt::WindowContextHelpButtonHint; bool hasMinimize = flags & Qt::WindowMinimizeButtonHint; bool hasMaximize = flags & Qt::WindowMaximizeButtonHint; bool paintAll = (DecorationRegion(decorationRegion) == All); bool handled = false; QStyle *style = QApplication::style(); // In the case of a borderless title bar, the title bar must be expanded one // borderWidth to the left, right and up. bool noTitleBorder = style->styleHint(QStyle::SH_TitleBar_NoBorder, 0, widget); int borderWidth = style->pixelMetric(QStyle::PM_MDIFrameWidth, 0, 0); int titleHeight = titleBarHeight(widget) + (noTitleBorder ? borderWidth : 0); int titleExtra = noTitleBorder ? borderWidth : 0; if ((paintAll || decorationRegion & Borders) && state == Normal && hasBorder) { QRegion newClip = painter->clipRegion(); if (hasTitle) { // reduce flicker QRect rect(widget->rect()); QRect r(rect.left() - titleExtra, rect.top() - titleHeight, rect.width() + 2 * titleExtra, titleHeight); newClip -= r; } if (!newClip.isEmpty()) { QRect br = QDecoration::region(widget).boundingRect(); painter->save(); painter->setClipRegion(newClip); QStyleOptionFrame opt; opt.palette = pal; opt.rect = br; opt.lineWidth = borderWidth; if (isActive) opt.state |= QStyle::State_Active; bool porterDuff = painter->paintEngine()->hasFeature(QPaintEngine::PorterDuff); if (porterDuff) painter->setCompositionMode(QPainter::CompositionMode_Source); painter->fillRect(br, pal.window()); if (porterDuff) painter->setCompositionMode(QPainter::CompositionMode_SourceOver); style->drawPrimitive(QStyle::PE_FrameWindow, &opt, painter, 0); painter->restore(); decorationRegion &= (~Borders); handled |= true; } } if (hasTitle) { painter->save(); QStyleOptionTitleBar opt; opt.subControls = (decorationRegion & Title ? QStyle::SC_TitleBarLabel : QStyle::SubControl(0)) | (decorationRegion & Menu ? QStyle::SC_TitleBarSysMenu : QStyle::SubControl(0)) | (decorationRegion & Help ? QStyle::SC_TitleBarContextHelpButton : QStyle::SubControl(0)) | (decorationRegion & Minimize ? QStyle::SC_TitleBarMinButton : QStyle::SubControl(0)) | (decorationRegion & Maximize ? QStyle::SC_TitleBarMaxButton : QStyle::SubControl(0)) | (decorationRegion & (Minimize | Maximize) ? QStyle::SC_TitleBarNormalButton : QStyle::SubControl(0)) | (decorationRegion & Close ? QStyle::SC_TitleBarCloseButton : QStyle::SubControl(0)); opt.titleBarFlags = widget->windowFlags(); opt.titleBarState = widget->windowState(); if (isActive) opt.titleBarState |= QStyle::State_Active; opt.text = windowTitleFor(widget); opt.icon = widget->windowIcon(); opt.palette = pal; opt.rect = QRect(widget->rect().x() - titleExtra, -titleHeight, widget->rect().width() + 2 * titleExtra, titleHeight); if (paintAll) { painter->setClipRegion(opt.rect); } else { const QRect widgetRect = widget->rect(); QRegion newClip = opt.rect; if (!(decorationRegion & Menu) && hasSysMenu) newClip -= region(widget, widgetRect, Menu); if (!(decorationRegion & Title) && hasTitle) newClip -= region(widget, widgetRect, Title); if (!(decorationRegion & Help) && hasContextHelp) newClip -= region(widget, widgetRect, Help); if (!(decorationRegion & Minimize) && hasMinimize) newClip -= region(widget, widgetRect, Minimize); if (!(decorationRegion & Maximize) && hasMaximize) newClip -= region(widget, widgetRect, Maximize); if (!(decorationRegion & (Minimize | Maximize)) && (hasMaximize | hasMinimize)) newClip -= region(widget, widgetRect, Normal); if (!(decorationRegion & Close)) newClip -= region(widget, widgetRect, Close); painter->setClipRegion(newClip); } if (state == Pressed) opt.activeSubControls = opt.subControls; style->drawComplexControl(QStyle::CC_TitleBar, &opt, painter, 0); painter->restore(); decorationRegion &= ~(Title | Menu | Help | Normalize | Minimize | Maximize | Close); handled |= true; } return handled; }
void TestComputeMaskedImage1DHistogram() { // // Single channel // { // typedef itk::Image<unsigned char, 2> ImageType; // ImageType::Pointer image = ImageType::New(); // ImageType::IndexType corner = {{0,0}}; // ImageType::SizeType size = {{100,100}}; // ImageType::RegionType region(corner, size); // image->SetRegions(region); // image->Allocate(); // itk::ImageRegionIterator<ImageType> imageIterator(image,region); // while(!imageIterator.IsAtEnd()) // { // if(imageIterator.GetIndex()[0] < 70) // { // imageIterator.Set(255); // } // else // { // imageIterator.Set(0); // } // ++imageIterator; // } // ImageType::PixelType rangeMin = 0; // ImageType::PixelType rangeMax = 255; // unsigned int numberOfBins = 10; // typedef int BinValueType; // typedef Histogram<BinValueType>::HistogramType HistogramType; // HistogramType histogram = Histogram<BinValueType>::ComputeImageHistogram1D(image.GetPointer(), // image->GetLargestPossibleRegion(), // numberOfBins, rangeMin, rangeMax); // Histogram<BinValueType>::OutputHistogram(histogram); // std::cout << std::endl; // } // Multi channel VectorImage { typedef itk::VectorImage<unsigned char, 2> ImageType; ImageType::Pointer image = ImageType::New(); ImageType::IndexType corner = {{0,0}}; ImageType::SizeType size = {{100,100}}; ImageType::RegionType region(corner, size); image->SetRegions(region); image->SetNumberOfComponentsPerPixel(3); image->Allocate(); Mask::Pointer mask = Mask::New(); mask->SetRegions(region); mask->Allocate(); itk::ImageRegionIterator<ImageType> imageIterator(image,region); while(!imageIterator.IsAtEnd()) { ImageType::PixelType pixel(image->GetNumberOfComponentsPerPixel()); if(imageIterator.GetIndex()[0] < 70) { for(unsigned int i = 0; i < pixel.GetSize(); ++i) { pixel[i] = 255; } } else { for(unsigned int i = 0; i < pixel.GetSize(); ++i) { pixel[i] = 0; } } imageIterator.Set(pixel); ++imageIterator; } // TypeTraits<ImageType::PixelType>::ComponentType rangeMin = 0; // TypeTraits<ImageType::PixelType>::ComponentType rangeMax = 255; ImageType::PixelType rangeMins; rangeMins.SetSize(image->GetNumberOfComponentsPerPixel()); rangeMins.Fill(0); ImageType::PixelType rangeMaxs; rangeMaxs.SetSize(image->GetNumberOfComponentsPerPixel()); rangeMaxs.Fill(255); unsigned int numberOfBinsPerComponent = 10; typedef int BinValueType; itk::ImageRegion<2> imageRegion = image->GetLargestPossibleRegion(); itk::ImageRegion<2> maskRegion = image->GetLargestPossibleRegion(); typedef MaskedHistogramGenerator<BinValueType> HistogramGeneratorType; typedef HistogramGeneratorType::HistogramType HistogramType; bool allowOutside = false; HistogramType histogram = HistogramGeneratorType::ComputeMaskedImage1DHistogram(image.GetPointer(), imageRegion, mask.GetPointer(), maskRegion, numberOfBinsPerComponent, rangeMins, rangeMaxs, allowOutside, HoleMaskPixelTypeEnum::VALID); histogram.Print(); std::cout << std::endl; } // // Multi channel Image<CovariantVector> // { // typedef itk::Image<itk::CovariantVector<unsigned char, 3>, 2> ImageType; // ImageType::Pointer image = ImageType::New(); // ImageType::IndexType corner = {{0,0}}; // ImageType::SizeType size = {{100,100}}; // ImageType::RegionType region(corner, size); // image->SetRegions(region); // image->Allocate(); // itk::ImageRegionIterator<ImageType> imageIterator(image,region); // while(!imageIterator.IsAtEnd()) // { // ImageType::PixelType pixel(image->GetNumberOfComponentsPerPixel()); // if(imageIterator.GetIndex()[0] < 70) // { // for(unsigned int i = 0; i < pixel.GetNumberOfComponents(); ++i) // { // pixel[i] = 255; // } // } // else // { // for(unsigned int i = 0; i < pixel.GetNumberOfComponents(); ++i) // { // pixel[i] = 0; // } // } // imageIterator.Set(pixel); // ++imageIterator; // } // TypeTraits<ImageType::PixelType>::ComponentType rangeMin = 0; // TypeTraits<ImageType::PixelType>::ComponentType rangeMax = 255; // unsigned int numberOfBinsPerComponent = 10; // typedef int BinValueType; // Histogram<BinValueType>::HistogramType histogram = Histogram<BinValueType>::ComputeImageHistogram1D(image.GetPointer(), // image->GetLargestPossibleRegion(), // numberOfBinsPerComponent, rangeMin, rangeMax); // Histogram<BinValueType>::OutputHistogram(histogram); // std::cout << std::endl; // } }
void pla_device::parse_fusemap() { jed_data jed; int result = JEDERR_NONE; // read pla file switch (m_format) { case PLA_FMT_JEDBIN: result = jedbin_parse(region()->base(), region()->bytes(), &jed); break; case PLA_FMT_BERKELEY: result = pla_parse(region()->base(), region()->bytes(), &jed); break; } if (result != JEDERR_NONE) { for (int p = 0; p < m_terms; p++) { m_term[p].and_mask = 0; m_term[p].or_mask = 0; } logerror("%s PLA parse error %d!\n", tag(), result); return; } // parse it UINT32 fusenum = 0; for (int p = 0; p < m_terms; p++) { term *term = &m_term[p]; // AND mask term->and_mask = 0; for (int i = 0; i < m_inputs; i++) { // complement term->and_mask |= (UINT64)jed_get_fuse(&jed, fusenum++) << (i + 32); // true term->and_mask |= (UINT64)jed_get_fuse(&jed, fusenum++) << i; } // OR mask term->or_mask = 0; for (int f = 0; f < m_outputs; f++) { term->or_mask |= !jed_get_fuse(&jed, fusenum++) << f; } term->or_mask <<= 32; } // XOR mask m_xor = 0; for (int f = 0; f < m_outputs; f++) { m_xor |= jed_get_fuse(&jed, fusenum++) << f; } m_xor <<= 32; }
/* * Propagation proper * */ ExecStatus Pack::propagate(Space& home, const ModEventDelta& med) { // Number of items int n = bs.size(); // Number of bins int m = l.size(); { Region region(home); // Possible sizes for bins int* s = region.alloc<int>(m); for (int j=m; j--; ) s[j] = 0; // Compute sizes for bins if (OffsetView::me(med) == ME_INT_VAL) { // Also eliminate assigned items int k=0; for (int i=0; i<n; i++) if (bs[i].assigned()) { int j = bs[i].bin().val(); l[j].offset(l[j].offset() - bs[i].size()); t -= bs[i].size(); } else { for (ViewValues<IntView> j(bs[i].bin()); j(); ++j) s[j.val()] += bs[i].size(); bs[k++] = bs[i]; } n=k; bs.size(n); } else { for (int i=n; i--; ) { assert(!bs[i].assigned()); for (ViewValues<IntView> j(bs[i].bin()); j(); ++j) s[j.val()] += bs[i].size(); } } // Propagate bin loads and compute lower and upper bound int min = t, max = t; for (int j=m; j--; ) { GECODE_ME_CHECK(l[j].gq(home,0)); GECODE_ME_CHECK(l[j].lq(home,s[j])); min -= l[j].max(); max -= l[j].min(); } // Propagate that load must be equal to total size for (bool mod = true; mod; ) { mod = false; ModEvent me; for (int j=m; j--; ) { int lj_min = l[j].min(); me = l[j].gq(home, min + l[j].max()); if (me_failed(me)) return ES_FAILED; if (me_modified(me)) { max += lj_min - l[j].min(); mod = true; } int lj_max = l[j].max(); me = l[j].lq(home, max + l[j].min()); if (me_failed(me)) return ES_FAILED; if (me_modified(me)) { min += lj_max - l[j].max(); mod = true; } } } if (n == 0) { assert(l.assigned()); return home.ES_SUBSUMED(*this); } { TellCache tc(region,m); int k=0; for (int i=0; i<n; i++) { for (ViewValues<IntView> j(bs[i].bin()); j(); ++j) { if (bs[i].size() > l[j.val()].max()) tc.nq(j.val()); if (s[j.val()] - bs[i].size() < l[j.val()].min()) tc.eq(j.val()); } GECODE_ES_CHECK(tc.tell(home,bs[i].bin())); // Eliminate assigned bin if (bs[i].assigned()) { int j = bs[i].bin().val(); l[j].offset(l[j].offset() - bs[i].size()); t -= bs[i].size(); } else { bs[k++] = bs[i]; } } n=k; bs.size(n); } } // Only if the propagator is at fixpoint here, continue with the more // expensive stage for propagation. if (IntView::me(modeventdelta()) != ME_INT_NONE) return ES_NOFIX; // Now the invariant holds that no more assigned bins exist! { Region region(home); // Size of items SizeSetMinusOne* s = region.alloc<SizeSetMinusOne>(m); for (int j=m; j--; ) s[j] = SizeSetMinusOne(region,n); // Set up size information for (int i=0; i<n; i++) { assert(!bs[i].assigned()); for (ViewValues<IntView> j(bs[i].bin()); j(); ++j) s[j.val()].add(bs[i].size()); } for (int j=m; j--; ) { // Can items still be packed into bin? if (nosum(static_cast<SizeSet&>(s[j]), l[j].min(), l[j].max())) return ES_FAILED; int ap, bp; // Must there be packed more items into bin? if (nosum(static_cast<SizeSet&>(s[j]), l[j].min(), l[j].min(), ap, bp)) GECODE_ME_CHECK(l[j].gq(home,bp)); // Must there be packed less items into bin? if (nosum(static_cast<SizeSet&>(s[j]), l[j].max(), l[j].max(), ap, bp)) GECODE_ME_CHECK(l[j].lq(home,ap)); } TellCache tc(region,m); int k=0; for (int i=0; i<n; i++) { assert(!bs[i].assigned()); for (ViewValues<IntView> j(bs[i].bin()); j(); ++j) { // Items must be removed in decreasing size! s[j.val()].minus(bs[i].size()); // Can item i still be packed into bin j? if (nosum(s[j.val()], l[j.val()].min() - bs[i].size(), l[j.val()].max() - bs[i].size())) tc.nq(j.val()); // Must item i be packed into bin j? if (nosum(s[j.val()], l[j.val()].min(), l[j.val()].max())) tc.eq(j.val()); } GECODE_ES_CHECK(tc.tell(home,bs[i].bin())); if (bs[i].assigned()) { int j = bs[i].bin().val(); l[j].offset(l[j].offset() - bs[i].size()); t -= bs[i].size(); } else { bs[k++] = bs[i]; } } n=k; bs.size(n); } // Perform lower bound checking if (n > 0) { Region region(home); // Find capacity estimate (we start from bs[0] as it might be // not packable, actually (will be detected later anyway)! int c = bs[0].size(); for (int j=m; j--; ) c = std::max(c,l[j].max()); // Count how many items have a certain size (bucket sort) int* n_s = region.alloc<int>(c+1); for (int i=c+1; i--; ) n_s[i] = 0; // Count unpacked items for (int i=n; i--; ) n_s[bs[i].size()]++; // Number of items and remaining bin load int nm = n; // Only count positive remaining bin loads for (int j=m; j--; ) if (l[j].max() < 0) { return ES_FAILED; } else if (c > l[j].max()) { n_s[c - l[j].max()]++; nm++; } // Sizes of items and remaining bin loads int* s = region.alloc<int>(nm); // Setup sorted sizes { int k=0; for (int i=c+1; i--; ) for (int n=n_s[i]; n--; ) s[k++]=i; assert(k == nm); } // Items in N1 are from 0 ... n1 - 1 int n1 = 0; // Items in N2 are from n1 ... n12 - 1, we count elements in N1 and N2 int n12 = 0; // Items in N3 are from n12 ... n3 - 1 int n3 = 0; // Free space in N2 int f2 = 0; // Total size of items in N3 int s3 = 0; // Initialize n12 and f2 for (; (n12 < nm) && (s[n12] > c/2); n12++) f2 += c - s[n12]; // Initialize n3 and s3 for (n3 = n12; n3 < nm; n3++) s3 += s[n3]; // Compute lower bounds for (int k=0; k<=c/2; k++) { // Make N1 larger by adding elements and N2 smaller for (; (n1 < nm) && (s[n1] > c-k); n1++) f2 -= c - s[n1]; assert(n1 <= n12); // Make N3 smaller by removing elements for (; (s[n3-1] < k) && (n3 > n12); n3--) s3 -= s[n3-1]; // Overspill int o = (s3 > f2) ? ((s3 - f2 + c - 1) / c) : 0; if (n12 + o > m) return ES_FAILED; } } return ES_NOFIX; }
bool PhysicalLocation::operator==(const PhysicalLocation& o) const { return country() == o.country() && region() == o.region() && locality() == o.locality() && area() == o.area() && street() == o.street() && building() == o.building() && floor() == o.floor() && room() == o.room() && postalcode() == o.postalcode() && text() == o.text(); }
TEST_F(LuaMobileTest, LuaSpawnManagerTest) { Vector<String> zoneNames; zoneNames.add("corellia"); zoneNames.add("dantooine"); zoneNames.add("dathomir"); zoneNames.add("endor"); zoneNames.add("lok"); zoneNames.add("naboo"); zoneNames.add("rori"); zoneNames.add("talus"); zoneNames.add("tatooine"); zoneNames.add("yavin4"); Lua* lua = new Lua(); lua->init(); for (int i = 0; i < zoneNames.size(); i++) { lua->runFile("scripts/managers/spawn_manager/" + zoneNames.get(i) + ".lua"); // Verify regions LuaObject regions = lua->getGlobalObject(zoneNames.get(i) + "_regions"); ASSERT_TRUE( regions.isValidTable() ) << "Regions table in " << zoneNames.get(i).toCharArray() << " spawn manager is invalid."; for (int j = 1; j <= regions.getTableSize(); ++j) { lua_rawgeti(regions.getLuaState(), -1, j); LuaObject region(regions.getLuaState()); ASSERT_TRUE( region.isValidTable() ) << "Invalid region table #" << String::valueOf(j).toCharArray() << " in " << zoneNames.get(i).toCharArray() << "_regions."; String area = region.getStringAt(1); int tier = region.getIntAt(5); if (tier & SpawnAreaMap::WORLDSPAWNAREA) { EXPECT_TRUE( tier & SpawnAreaMap::SPAWNAREA ) << "World spawn area " << std::string(area.toCharArray()) << " on planet " << std::string(zoneNames.get(i).toCharArray()) << " is not a spawn area."; } if (tier & SpawnAreaMap::SPAWNAREA) { LuaObject spawnGroups = region.getObjectAt(6); ASSERT_TRUE( spawnGroups.isValidTable() ) << "Invalid spawnGroups table in spawn area " << std::string(area.toCharArray()) << " in " << zoneNames.get(i).toCharArray() << "_regions."; for (int k = 1; k <= spawnGroups.getTableSize(); k++) { String group = spawnGroups.getStringAt(k); EXPECT_TRUE( CreatureTemplateManager::instance()->getSpawnGroup(group.hashCode()) != NULL ) << "Spawn group " << std::string(group.toCharArray()) << " for spawn area " << std::string(area.toCharArray()) << " on planet " << std::string(zoneNames.get(i).toCharArray()) << " does not exist."; } spawnGroups.pop(); } region.pop(); } regions.pop(); // Verify static spawns LuaObject spawns = lua->getGlobalObject(zoneNames.get(i) + "_static_spawns"); ASSERT_TRUE( spawns.isValidTable() ) << "Static spawns table in " << zoneNames.get(i).toCharArray() << " spawn manager is invalid."; for (int j = 1; j <= spawns.getTableSize(); ++j) { lua_rawgeti(spawns.getLuaState(), -1, j); LuaObject spawn(spawns.getLuaState()); ASSERT_TRUE( spawn.isValidTable() ) << "Invalid spawn table #" << String::valueOf(j).toCharArray() << " in " << zoneNames.get(i).toCharArray() << "_static_spawns."; String name = spawn.getStringAt(1); EXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(name) != NULL ) << "Static spawn " << std::string(name.toCharArray()) << " on planet " << std::string(zoneNames.get(i).toCharArray()) << " is not valid"; spawn.pop(); } spawns.pop(); } delete lua; }
void numeric_spinner::handle_event(event::ptr e) { switch (e->type()) { case event::key_down: { key_event::ptr ke = boost::shared_static_cast<key_event>(e); switch ( ke->fn_key() ) { case key_enter: case key_uparrow: value_ = value_+increment_; if (value_ > max_) { if (wrap_) value_ = min_; else value_ = max_; } build_label(); on_change(); redraw(rect()); return; break; case key_downarrow: value_ = value_-increment_; if (value_ < min_) { if (wrap_) value_ = max_; else value_ = min_; } build_label(); on_change(); redraw(rect()); return; break; } break; } case event::mouse_up: { mouse_event::ptr me = boost::shared_static_cast<mouse_event>(e); if (region(me->x(), me->y()) == DOWN_ARROW) { value_ = value_-increment_; if (value_ < min_) { if (wrap_) value_ = max_; else value_ = min_; } } else { value_ = value_+increment_; if (value_ > max_) { if (wrap_) value_ = min_; else value_ = max_; } } build_label(); on_change(); redraw(rect()); return; } } widget::handle_event(e); }
void PrintLayout::printTable() { // create and setup a table QTableView table; table.setAttribute(Qt::WA_DontShowOnScreen); table.setSelectionMode(QAbstractItemView::NoSelection); table.setFocusPolicy(Qt::NoFocus); table.horizontalHeader()->setVisible(false); table.horizontalHeader()->setResizeMode(QHeaderView::Fixed); table.verticalHeader()->setVisible(false); table.verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); table.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // fit table to one page initially table.resize(scaledPageW, scaledPageH); // create and fill a table model TablePrintModel model; struct dive *dive; int i, row = 0; addTablePrintHeadingRow(&model, row); // add one heading row row++; for_each_dive(i, dive) { if (!dive->selected && printOptions->print_selected) continue; addTablePrintDataRow(&model, row, dive); row++; } table.setModel(&model); // set model to table // resize columns to percentages from page width for (int i = 0; i < model.columns; i++) { int pw = qCeil((qreal)(tablePrintColumnWidths.at(i) * table.width()) / 100); table.horizontalHeader()->resizeSection(i, pw); } // reset the model at this point model.callReset(); // a list of vertical offsets where pages begin and some helpers QList<unsigned int> pageIndexes; pageIndexes.append(0); int tableHeight = 0, rowH = 0, accH = 0; // process all rows for (int i = 0; i < model.rows; i++) { rowH = table.rowHeight(i); accH += rowH; if (accH > scaledPageH) { // push a new page index and add a heading pageIndexes.append(pageIndexes.last() + (accH - rowH)); addTablePrintHeadingRow(&model, i); accH = 0; i--; } tableHeight += rowH; } pageIndexes.append(pageIndexes.last() + accH); // resize the whole widget so that it can be rendered table.resize(scaledPageW, tableHeight); // attach a painter and render pages by using pageIndexes QPainter painter(printer); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::SmoothPixmapTransform); painter.scale(scaleX, scaleY); for (int i = 0; i < pageIndexes.size() - 1; i++) { if (i > 0) printer->newPage(); QRegion region(0, pageIndexes.at(i) - 1, table.width(), pageIndexes.at(i + 1) - pageIndexes.at(i) + 2); table.render(&painter, QPoint(0, 0), region); } }
// Compute single tracking score TrackingScore* TrackingEvaluator::computeScore(const TrackedObject& tracked_object, const Mat& frame, int frame_number, TrackingScoreHistory *history) { // Create score TrackingScore* score = new TrackingScore(&nbc); // Add score to history history->addScore(score, frame_number); // Get blob const cvb::CvBlob& orig_blob = tracked_object.currentRegion(); // Random move blobs - to test certainties cvb::CvBlob blob; cvCloneBlob(orig_blob, blob); // Save shape ratio score->setShapeRatio(((float)blob.width())/((float)blob.height())); // Save area score->setArea(blob.width()*blob.height()); // Compute object's binary mask, for the histogram Mat mask = drawBlob(blob, true, frame.cols, frame.rows); // Get grayscale frame Mat frame_gs; cvtColor(frame, frame_gs, CV_BGR2GRAY); // Split the color channels Mat* channels = new Mat[3]; split(frame, channels); Mat frame_b = channels[0]; Mat frame_g = channels[1]; Mat frame_r = channels[2]; delete [] channels; // Compute histograms Histogram hist_gs(frame_gs, mask); Histogram hist_r(frame_r, mask); Histogram hist_g(frame_g, mask); Histogram hist_b(frame_b, mask); // Save histogram score->setHistograms(hist_gs, hist_r, hist_g, hist_b); // Select part of frame on which to compute the texture features Mat copy_gs = frame_gs.clone(); // Blacken non-mask pixels for(unsigned int x=blob.x; x<=blob.maxx; x++) { for(unsigned int y=blob.y; y<=blob.maxy; y++) { if(mask.at<uchar>(y,x) == 0) { copy_gs.at<uchar>(y,x) = 0; } } } // Crop image Rect region(blob.x, blob.y, blob.width(), blob.height()); Mat texture_input = copy_gs(region); // Compute texture features for this object vector<float> texture_features = GaborFilter::applyFilterSet(texture_input, gabor_scales, parameters.get<int>("num_orientations"), false, 1, 0.5, 101); // Save texture features score->setTextureFeatures(texture_features); // Set temporal score to the number of appearances score->temporal_score = history->numScores(); // Get the frame number of the previous detection of this object, if available int prev_frame = -1; TrackingScore* prev_score = NULL; cvb::CvBlob prev_blob; if(history->numScores() > 1) { // Read frame number prev_frame = *(tracked_object.frameList().end() - 2); // Get previous score prev_score = (TrackingScore*) history->getScore(prev_frame); // Get previous blob prev_blob = *(tracked_object.regionList().end() - 2); // Compute shape ratio score score->shape_ratio_score = computeShapeRatioScore(prev_score->getShapeRatio(), score->getShapeRatio()); // Compute area score score->area_score = computeAreaScore(prev_score->getArea(), score->getArea()); // Compute histogram difference score score->histogram_diff_score = computeHistogramDiffScore(score, prev_score); // Compute texture difference score score->texture_diff_score = computeTextureDiffScore(score->getTextureFeatures(), prev_score->getTextureFeatures()); // Compute velocity for this score Point2f prev_position((prev_blob.maxx+prev_blob.x)/2, (prev_blob.maxy+prev_blob.y)/2); Point2f curr_position((blob.maxx+blob.x)/2, (blob.maxy+blob.y)/2); float velocity = sqrt((prev_position.x-curr_position.x)*(prev_position.x-curr_position.x) + (prev_position.y-curr_position.y)*(prev_position.y-curr_position.y)); score->setVelocity(velocity); // Add velocity to the accumulated velocity for this object (will be used to compute an average according to the number of detections) history->accumulateVelocity(velocity); // Check if the previous score has its velocity set if(prev_score->getVelocity() > 0) { //cout << "computing ms: " << score->getVelocity() << ", " << history->getAverageVelocity() << endl; // Compute motion smoothness score, based on current velocity and average velocity score->motion_smoothness = computeMotionSmoothnessScore(score->getVelocity(), history->getAverageVelocity()); } else { // Set score to 0 score->motion_smoothness = 0.0f; // Mark score as not full score->full = false; } // Compute direction for this score float direction = fastAtan2(-curr_position.y + prev_position.y, curr_position.x - prev_position.x); score->setDirection(direction); // Check if the previous score has its direction set //cout << "direction: " << direction << ", prev_score direction: " << prev_score->getDirection() << endl; if(prev_score->getDirection() > 0) { //cout << "computing d : " << prev_score->getDirection() << ", " << score->getDirection() << endl; // Compute direction score, based on current direction and previous direction score->direction_score = computeDirectionScore(score->getDirection(), prev_score->getDirection()); } else { // Set score to 0 score->direction_score = 0.0f; // Mark score as not full score->full = false; } //if(score->full)// && (frame_number % 10) == 0) //{ // out_file << score->shape_ratio_score << " " << score->area_score << " " << score->histogram_diff_score << " " << score->motion_smoothness << " " << score->direction_score << " " << score->texture_diff_score << " 1" << endl; // cout << score->shape_ratio_score << " " << score->area_score << " " << score->histogram_diff_score << " " << score->motion_smoothness << " " << score->direction_score << " " << score->texture_diff_score << " 1" << endl; //} //out_file << score->shape_ratio_score << " " << score->histogram_diff_score << " 1"; //if(pd) // out_file << score->value() << endl; } else { // Set score as certain score->certain = true; } Log::debug() << "tracking score: " << score->value() << "(" << score->shape_ratio_score << ", " << score->area_score << ", " << score->histogram_diff_score << ", " << (score->full ? score->motion_smoothness : -1) << ", " << (score->full ? score->direction_score : -1 ) << ", " << score->texture_diff_score << ")" << endl; // Return score return score; }
void frmAbout::SetWindowShape() { wxRegion region(about); SetShape(region); }
uint xselect(Frame *f, Mousectl *mc, Image *col, uint *p1p) /* when called, button is down */ { uint p0, p1, q, tmp; ulong msec; Point mp, pt0, pt1, qt; int reg, b; mp = mc->xy; b = mc->buttons; msec = mc->msec; /* remove tick */ if(f->p0 == f->p1) frtick(f, frptofchar(f, f->p0), 0); p0 = p1 = frcharofpt(f, mp); pt0 = frptofchar(f, p0); pt1 = frptofchar(f, p1); reg = 0; frtick(f, pt0, 1); do { q = frcharofpt(f, mc->xy); if(p1 != q) { if(p0 == p1) frtick(f, pt0, 0); if(reg != region(q, p0)) { /* crossed starting point; reset */ if(reg > 0) selrestore(f, pt0, p0, p1); else if(reg < 0) selrestore(f, pt1, p1, p0); p1 = p0; pt1 = pt0; reg = region(q, p0); if(reg == 0) frdrawsel0(f, pt0, p0, p1, col, display->white); } qt = frptofchar(f, q); if(reg > 0) { if(q > p1) frdrawsel0(f, pt1, p1, q, col, display->white); else if(q < p1) selrestore(f, qt, q, p1); } else if(reg < 0) { if(q > p1) selrestore(f, pt1, p1, q); else frdrawsel0(f, qt, q, p1, col, display->white); } p1 = q; pt1 = qt; } if(p0 == p1) frtick(f, pt0, 1); flushimage(f->display, 1); readmouse(mc); } while(mc->buttons == b); if(mc->msec-msec < DELAY && p0!=p1 && abs(mp.x-mc->xy.x)<MINMOVE && abs(mp.y-mc->xy.y)<MINMOVE) { if(reg > 0) selrestore(f, pt0, p0, p1); else if(reg < 0) selrestore(f, pt1, p1, p0); p1 = p0; } if(p1 < p0) { tmp = p0; p0 = p1; p1 = tmp; } pt0 = frptofchar(f, p0); if(p0 == p1) frtick(f, pt0, 0); selrestore(f, pt0, p0, p1); /* restore tick */ if(f->p0 == f->p1) frtick(f, frptofchar(f, f->p0), 1); flushimage(f->display, 1); *p1p = p1; return p0; }
void StyledButton::paintEvent(QPaintEvent *ev) { QPainter p(this); // Initialize button style options QStyleOptionButton opt; initStyleOption(&opt); // Determine colour set to paint with QColor topCol(*(m_colorSet.topColor)); QColor bottomCol(*(m_colorSet.bottomColor)); QColor highlightCol(*(m_colorSet.highlightColor)); QColor shadowCol(*(m_colorSet.shadowColor)); StyleHelper::ColorSet set(&topCol, &bottomCol, &highlightCol, &shadowCol); if(m_hovered) { topCol = topCol.darker(BUTTON_HOVER_DARKEN_AMOUNT); bottomCol = bottomCol.darker(BUTTON_HOVER_DARKEN_AMOUNT); highlightCol = highlightCol.darker(BUTTON_HOVER_DARKEN_AMOUNT); shadowCol = shadowCol.darker(BUTTON_HOVER_DARKEN_AMOUNT); } opt.palette.setColor(QPalette::ButtonText, m_textColor); // Draw background StyleHelper::drawBackground( &p, QRect(0, 0, width(), height()), set, opt.state & QStyle::State_Sunken, 0.0f, m_joinLeft, m_joinRight); //------------------------------------------------------------------------- // This section duplicated in `DarkStyle` (CE_PushButtonLabel) // The only difference is that we hard-code the pressed button offset // Get contents rectangle QMargins margins = contentsMargins(); QStyleOptionButton subopt = opt; subopt.rect = opt.rect.adjusted( margins.left(), margins.top(), -margins.right(), -margins.bottom()); QRect textRect = subopt.rect; uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic; if(!style()->styleHint(QStyle::SH_UnderlineShortcut, &subopt, this)) tf |= Qt::TextHideMnemonic; // Draw the icon if one exists. We need to modify the text rectangle as // well as we want both the icon and the text centered on the button QRect iconRect; if(!subopt.icon.isNull()) { // Determine icon state QIcon::Mode mode = (subopt.state & QStyle::State_Enabled) ? QIcon::Normal : QIcon::Disabled; if(mode == QIcon::Normal && subopt.state & QStyle::State_HasFocus) mode = QIcon::Active; QIcon::State state = QIcon::Off; if(subopt.state & QStyle::State_On) state = QIcon::On; // Determine metrics QPixmap pixmap = subopt.icon.pixmap(subopt.iconSize, mode, state); int labelWidth = pixmap.width(); int labelHeight = pixmap.height(); int iconSpacing = 4; // See `sizeHint()` int textWidth = subopt.fontMetrics.boundingRect( subopt.rect, tf, subopt.text).width(); if(!subopt.text.isEmpty()) labelWidth += textWidth + iconSpacing; // Determine icon rectangle iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2, textRect.y() + (textRect.height() - labelHeight) / 2, pixmap.width(), pixmap.height()); iconRect = QStyle::visualRect(subopt.direction, textRect, iconRect); // Change where the text will be displayed tf |= Qt::AlignLeft; // Left align, we adjust the text rect instead if(subopt.direction == Qt::RightToLeft) textRect.setRight(iconRect.left() - iconSpacing); else textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing); // Translate the contents slightly when the button is pressed if(subopt.state & QStyle::State_Sunken) iconRect.translate(1, 1); // Draw pixmap p.drawPixmap(iconRect, pixmap); } else tf |= Qt::AlignHCenter; // HACK: Move the text up 1px so that it is vertically centered textRect.translate(0, -1); // Translate the contents slightly when the button is pressed if(subopt.state & QStyle::State_Sunken) textRect.translate(1, 1); // Draw text shadow only if the button is enabled if(subopt.state & QStyle::State_Enabled) { QPalette pal(subopt.palette); pal.setColor(QPalette::ButtonText, m_textShadowColor); style()->drawItemText( &p, textRect.translated(2, 1).adjusted(-1, -1, 1, 1), tf, pal, true, subopt.text, QPalette::ButtonText); } // Draw text. HACK: We offset the text by one pixel to the right as the // font metrics include the character spacing to the right of the last // character making the text appear slightly to the left. We also increase // the rectangle by 1px in every direction in order for the text to not get // clipped with some fonts. style()->drawItemText( &p, textRect.translated(1, 0).adjusted(-1, -1, 1, 1), tf, subopt.palette, (subopt.state & QStyle::State_Enabled), subopt.text, QPalette::ButtonText); //------------------------------------------------------------------------- // This section is based off QCommonStyle (CE_PushButton) // We change the way the focus rectangle is calculated as the original // algorithm has some bugs // Draw focus rectangle if(hasFocus()) { int pad = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this) + 1; QStyleOptionFocusRect fropt; fropt.initFrom(this); fropt.QStyleOption::operator=(opt); // Determine bounding rectangle if(!subopt.icon.isNull()) { QRegion region(subopt.fontMetrics.boundingRect( textRect, tf, subopt.text)); region += iconRect; fropt.rect = region.boundingRect(); fropt.rect = fropt.rect.adjusted(-pad, -pad, pad, pad); } else if(!subopt.text.isEmpty()) { fropt.rect = subopt.fontMetrics.boundingRect( textRect, tf, subopt.text); fropt.rect = fropt.rect.adjusted(-pad, -pad, pad, pad); } else { fropt.rect = subopt.rect; // Translate the contents slightly when the button is pressed if(subopt.state & QStyle::State_Sunken) fropt.rect.translate(1, 1); } style()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, &p, this); //p.drawRect(fropt.rect); } //------------------------------------------------------------------------- }
TEST_F(TestRegionNoArgs,BasicRegionInteractions1) { typedef TestConcurrentCompositeStateNoArgsMock < TestStateMachineNoEventArgsMock > ConcurrentCompositeStateMockType; typedef TestRegionNoArgsMock < ConcurrentCompositeStateMockType , sttcl::CompositeStateHistoryType::None > RegionMockType; ::testing::NiceMock<TestStateMachineNoEventArgsMock> stateMachine; ::testing::NiceMock < ConcurrentCompositeStateMockType > compositeState(&stateMachine); ::testing::NiceMock < RegionMockType > region(&compositeState); ::testing::NiceMock < TestRegionInnerStateNoArgsMock<ConcurrentCompositeStateMockType,RegionMockType> > innerState; stateMachine.autoFinalize(false); compositeState.setRegion(0,®ion); region.initialState(&innerState); stateMachine.initialState(&compositeState); // Setup mock call expectations //---------------------------------------------------------------------------- // Check region calls EXPECT_CALL(region,enterRegionImpl(&compositeState)) .Times(1); EXPECT_CALL(region,startingRegionThread()) .Times(1); EXPECT_CALL(region,initializeImpl(_)) .Times(1); EXPECT_CALL(region,finalizeImpl(_)) .Times(1); EXPECT_CALL(region,endingRegionThread()) .Times(1); EXPECT_CALL(region,exitRegionImpl(&compositeState)) .Times(1); EXPECT_CALL(innerState,entryImpl(®ion)) .Times(1); EXPECT_CALL(innerState,startDoImpl(®ion)) .Times(1); EXPECT_CALL(innerState,initSubStateMachinesImpl(_)) .Times(1); EXPECT_CALL(innerState,endDoImpl(®ion)) .Times(1); EXPECT_CALL(innerState,exitImpl(®ion)) .Times(1); // Run the state machine //---------------------------------------------------------------------------- STTCL_TEST_LOG_ALL(); stateMachine.initialize(); // Give the region thread(s) a chance to run sttcl::internal::SttclThread<>::sleep(sttcl::TimeDuration<>(0,0,0,100)); stateMachine.finalize(false); STTCL_TEST_LOG_END(); }
void Shot::roiRegionLarger(const Size &minSize, bool useBinning) { FCam::Rect region(0,0, minSize.width, minSize.height); roiRegionLarger(region, useBinning); }
int main (int argc, char *argv[]) { if(argc != 7) { std::cerr << "Required arguments: InputFilename.ptx startX startY sizeX sizeY OutputPrefix" << std::endl; return EXIT_FAILURE; } std::string inputFileName = argv[1]; std::string strStartX = argv[2]; std::string strStartY = argv[3]; std::string strSizeX = argv[4]; std::string strSizeY = argv[5]; std::string outputFileName = argv[6]; unsigned int startX, startY, sizeX, sizeY; std::stringstream ss; ss.str(strStartX); ss >> startX; ss.clear(); ss.str(strStartY); ss >> startY; ss.clear(); ss.str(strSizeX); ss >> sizeX; ss.clear(); ss.str(strSizeY); ss >> sizeY; ss.clear(); std::cout << "Input filename: " << inputFileName << std::endl; std::cout << "Output filename: " << outputFileName << std::endl; std::cout << "start X: " << startX << std::endl; std::cout << "start Y: " << startY << std::endl; std::cout << "size X: " << sizeX << std::endl; std::cout << "size Y: " << sizeY << std::endl; itk::Index<2> start; start[0] = startX; start[1] = startY; itk::Size<2> size; size[0] = sizeX; size[1] = sizeY; itk::ImageRegion<2> region(start,size); std::cout << "Crop region: " << region << std::endl; std::cout << "Reading PTX..." << std::endl; PTXImage ptxImage = PTXReader::Read(inputFileName); std::cout << "Cropping..." << std::endl; ptxImage.Crop(region); std::cout << "Writing output..." << std::endl; ptxImage.WritePTX(outputFileName); return EXIT_SUCCESS; }
void Shot::roiRegionSmaller(const Size &maxSize, bool useBinning) { FCam::Rect region(0,0, maxSize.width, maxSize.height); roiRegionSmaller(region, useBinning); }
void ExtractTexto::findSuperRect(std::vector<cv::Rect> const &locations, std::vector<cv::Rect> & new_locations) { unsigned j, k; ExtractTexto::regions regiones; int pos, NumRect, prioridad; int areaOriginal, areaRegion, areaIntersect; for (j = 0; j < locations.size(); j++) { unsigned regionSize = regiones.reg.size(); areaOriginal = locations[j].area(); pos = -1; NumRect = 1; prioridad = 1; for ( k = 0; k < regionSize; k++ ){ cv::Rect rectIntersect = locations[j] & regiones.reg[k].Reg; areaRegion = regiones.reg[k].Reg.area(); areaIntersect = rectIntersect.area(); if ( areaIntersect > 0.80 * areaRegion ){ //Original contiene a Reg regiones.reg[k].prioridad++; if ( areaIntersect > 0.80 * areaOriginal && pos < 0 ){ //Reg contiene a Original pos = k; regiones.reg[k].numRect++; } } else if( areaIntersect > 0.80 * areaOriginal ){ //Reg contiene a Original prioridad += regiones.reg[k].numRect; } } if ( pos >= 0 ) { if ( regiones.reg[pos].Reg.area() < areaOriginal ){ regiones.reg[pos].Reg = locations[j]; } } else{ regiones.reg.push_back(region(locations[j], NumRect, prioridad)); } } regiones.ordenarPrioritarios(); regiones.copiarRegiones(new_locations); }
/*! \reimp */ bool Q3GroupBox::event(QEvent *e) { if (e->type()==QEvent::Paint) { QStyleOptionGroupBox opt; initStyleOption(&opt); opt.lineWidth=d->lineWidth; opt.midLineWidth=d->midLineWidth; QPainter p(this); if (frameShape()==GroupBoxPanel) { style()->drawComplexControl(QStyle::CC_GroupBox, &opt, &p, this); } else { //in case it is a Paint event with a frame shape different from the group box const QRect textRect = style()->subControlRect(QStyle::CC_GroupBox, &opt, QStyle::SC_GroupBoxLabel, this); const QRect checkBoxRect = style()->subControlRect(QStyle::CC_GroupBox, &opt, QStyle::SC_GroupBoxCheckBox, this); // Draw title if ((opt.subControls & QStyle::SC_GroupBoxLabel) && !opt.text.isEmpty()) { QColor textColor = opt.textColor; if (textColor.isValid()) p.setPen(textColor); int alignment = int(opt.textAlignment); if (!style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, this)) alignment |= Qt::TextHideMnemonic; style()->drawItemText(&p, textRect, Qt::TextShowMnemonic | Qt::AlignHCenter | alignment, opt.palette, opt.state & QStyle::State_Enabled, opt.text, textColor.isValid() ? QPalette::NoRole : QPalette::WindowText); if (opt.state & QStyle::State_HasFocus) { QStyleOptionFocusRect fropt; fropt.QStyleOption::operator=(opt); fropt.rect = textRect; style()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, &p, this); } } // Draw checkbox if (opt.subControls & QStyle::SC_GroupBoxCheckBox) { QStyleOptionButton box; box.QStyleOption::operator=(opt); box.rect = checkBoxRect; style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &box, &p, this); } //sets clipping QRegion region(rect()); if (!title().isEmpty()) { bool ltr = layoutDirection() == Qt::LeftToRight; QRect finalRect = checkBoxRect.united(textRect); if (isCheckable()) finalRect.adjust(ltr ? -4 : 0, 0, ltr ? 0 : 4, 0); region -= finalRect; } p.setClipRegion(region); drawFrame(&p); } return false; } return QGroupBox::event(e); }
Py::Object agg_to_gtk_drawable(const Py::Tuple &args) { // args are gc, renderer, bbox where bbox is a transforms BBox // (possibly None). If bbox is None, blit the entire agg buffer // to gtk. If bbox is not None, blit only the region defined by // the bbox args.verify_length(3); PyGObject *py_drawable = (PyGObject *)(args[0].ptr()); RendererAgg* aggRenderer = static_cast<RendererAgg*>(args[1].ptr()); GdkDrawable *drawable = GDK_DRAWABLE(py_drawable->obj); GdkGC* gc = gdk_gc_new(drawable); int srcstride = aggRenderer->get_width()*4; int srcwidth = (int)aggRenderer->get_width(); int srcheight = (int)aggRenderer->get_height(); // these three will be overridden below int destx = 0; int desty = 0; int destwidth = 1; int destheight = 1; int deststride = 1; bool needfree = false; agg::int8u *destbuffer = NULL; if (args[2].ptr() == Py_None) { //bbox is None; copy the entire image destbuffer = aggRenderer->pixBuffer; destwidth = srcwidth; destheight = srcheight; deststride = srcstride; } else { //bbox is not None; copy the image in the bbox PyObject* clipbox = args[2].ptr(); double l, b, r, t; if (!py_convert_bbox(clipbox, l, b, r, t)) { throw Py::TypeError ("Argument 3 to agg_to_gtk_drawable must be a Bbox object."); } destx = (int)l; desty = srcheight-(int)t; destwidth = (int)(r-l); destheight = (int)(t-b); deststride = destwidth*4; needfree = true; destbuffer = new agg::int8u[deststride*destheight]; if (destbuffer ==NULL) { throw Py::MemoryError("_gtkagg could not allocate memory for destbuffer"); } agg::rendering_buffer destrbuf; destrbuf.attach(destbuffer, destwidth, destheight, deststride); pixfmt destpf(destrbuf); renderer_base destrb(destpf); //destrb.clear(agg::rgba(1, 1, 1, 0)); agg::rect_base<int> region(destx, desty, (int)r, srcheight-(int)b); destrb.copy_from(*aggRenderer->renderingBuffer, ®ion, -destx, -desty); } /*std::cout << desty << " " << destheight << " " << srcheight << std::endl;*/ //gdk_rgb_init(); gdk_draw_rgb_32_image(drawable, gc, destx, desty, destwidth, destheight, GDK_RGB_DITHER_NORMAL, destbuffer, deststride); if (needfree) delete [] destbuffer; return Py::Object(); }
JNIEXPORT jbyteArray JNICALL Java_org_witness_informacam_informa_embed_ImageConstructor_redactRegion(JNIEnv *env, jobject obj, jstring jstrSrcFilename, jstring jstrDestFilename, int left, int right, int top, int bottom, jstring jStrRedactionCommand) { const char* TAG = "*************INFORMA_JNI***************"; const char* PROC = "JPEGREDACTION"; __android_log_write(ANDROID_LOG_ERROR, PROC, "Running"); unsigned int newPackSize = 0; jbyteArray returnedPack; try { jpeg_redaction::Jpeg jpeg_decoder; const char* strSrcFilename; const char* strDestFilename; const char* strRedactionCommand; strSrcFilename = (env)->GetStringUTFChars(jstrSrcFilename , NULL); strDestFilename = (env)->GetStringUTFChars(jstrDestFilename , NULL); strRedactionCommand = (env)->GetStringUTFChars(jStrRedactionCommand , NULL); jpeg_decoder.LoadFromFile(strSrcFilename, true); __android_log_write(ANDROID_LOG_ERROR, PROC, "Loaded"); __android_log_write(ANDROID_LOG_ERROR, PROC, strSrcFilename); // do the redaction on this region jpeg_redaction::Redaction::Region region(left, right, top, bottom); region.SetRedactionMethod(strRedactionCommand); jpeg_redaction::Redaction redaction; redaction.AddRegion(region); __android_log_write(ANDROID_LOG_ERROR,"JPEGREDACTION","added redact region"); jpeg_decoder.DecodeImage(&redaction,NULL); __android_log_write(ANDROID_LOG_ERROR,"JPEGREDACTION","redacted"); // get this region's redaction pack std::vector<unsigned char> redactionPack; redaction.Pack(&redactionPack); newPackSize = redactionPack.size(); returnedPack = (jbyteArray) env->NewByteArray(newPackSize); jbyte buffer[newPackSize]; for(int i=0; i<redactionPack.size(); i++) { buffer[i] = redactionPack.at(i); } env->SetByteArrayRegion(returnedPack, 0, newPackSize, buffer); __android_log_write(ANDROID_LOG_DEBUG, TAG, "added one new redaction pack"); jpeg_decoder.Save(strDestFilename); __android_log_write(ANDROID_LOG_ERROR,"JPEGREDACTION","saved"); (env)->ReleaseStringUTFChars(jstrSrcFilename , strSrcFilename); // release jstring (env)->ReleaseStringUTFChars(jstrDestFilename , strDestFilename); // release jstring } catch (const char *error) { __android_log_write(ANDROID_LOG_ERROR,"JPEGREDACTION","ERROR"); __android_log_write(ANDROID_LOG_ERROR,"JPEGREDACTION", error); } __android_log_write(ANDROID_LOG_ERROR,"JPEGREDACTION","Finished"); return returnedPack; }
void nile_device::device_start() { m_sound_ram = region()->base(); m_stream = stream_alloc(0, 2, 44100); }
QT_BEGIN_NAMESPACE /*! \class QDecoration \ingroup qws \brief The QDecoration class is a base class for window decorations in Qt for Embedded Linux Note that this class is non-portable and only available in \l{Qt for Embedded Linux}. \l{Qt for Embedded Linux} provides window management of top level windows and several ready made decorations (i.e., \c Default, \c Styled and \c Windows). Custom decorations can be implemented by subclassing the QDecoration class and creating a decoration plugin (derived from QDecorationPlugin). The default implementation of the QDecorationFactory class will automatically detect the plugin, and load the decoration into the application at run-time using Qt's \l {How to Create Qt Plugins}{plugin system}. To actually apply a decoration, use the QApplication::qwsSetDecoration() function. When creating a custom decoration, implement the paint() function to paint the border and title decoration, and the region() function to return the regions the decoration occupies. Reimplement the regionClicked() and regionDoubleClicked() functions to respond to mouse clicks (the default implementations responds to (single) clicks on items in a widget's system menu and double clicks on a widget's title). QDecoration provides the DecorationRegion enum that describes the various regions of the window decoration, and the regionAt() function to determine the region containing a given point. The QDecoration class also provides the DecorationState enum describing the state of a given region, e.g. whether it is active or not. In addition, it is possible to build the system menu for a given top level widget using the buildSysMenu() function; whenever an action in this menu is triggered, the menuTriggered() function is called automatically. Finally, the QDecoration class provides a couple of static functions, startMove() and startResize(), which start a move or resize action by making the appropriate decoration region active and grabbing the mouse input. \sa QDecorationFactory, QDecorationPlugin, {Qt for Embedded Linux Architecture} */ /*! \fn QDecoration::QDecoration() Constructs a decoration object. */ /*! \fn QDecoration::~QDecoration() Destroys this decoration object. */ /*! \enum QDecoration::DecorationRegion This enum describes the various regions of the window decoration. \value All The entire region used by the window decoration. \value Top The top border used to vertically resize the window. \value Bottom The bottom border used to vertically resize the window. \value Left The left border used to horizontally resize the window. \value Right The right border used to horizontally resize the window. \value TopLeft The top-left corner of the window used to resize the window both horizontally and vertically. \value TopRight The top-right corner of the window used to resize the window both horizontally and vertically. \value BottomLeft The bottom-left corner of the window used to resize the window both horizontally and vertically. \value BottomRight The bottom-right corner of the window used to resize the window both horizontally and vertically. \value Borders All the regions used to describe the window's borders. \value Title The region containing the window title, used to move the window by dragging with the mouse cursor. \value Close The region occupied by the close button. Clicking in this region closes the window. \value Minimize The region occupied by the minimize button. Clicking in this region minimizes the window. \value Maximize The region occupied by the maximize button. Clicking in this region maximizes the window. \value Normalize The region occupied by a button used to restore a window's normal size. Clicking in this region restores a maximized window to its previous size. The region used for this button is often also the Maximize region. \value Menu The region occupied by the window's menu button. Clicking in this region opens the window operations (system) menu. \value Help The region occupied by the window's help button. Clicking in this region causes the context-sensitive help function to be enabled. \value Resize The region used to resize the window. \value Move The region used to move the window. \value None No region. \sa region(), regionAt(), DecorationState */ /*! \enum QDecoration::DecorationState This enum describes the various states of a decoration region. \value Normal The region is active \value Disabled The region is inactive. \value Hover The cursor is hovering over the region. \value Pressed The region is pressed. \sa paint(), DecorationRegion */ /*! \fn QRegion QDecoration::region(const QWidget *widget, const QRect & rectangle, int decorationRegion) Implement this function to return the region specified by \a decorationRegion for the given top level \a widget. The \a rectangle parameter specifies the rectangle the decoration is wrapped around. The \a decorationRegion is a bitmask of the values described by the DecorationRegion enum. \sa regionAt(), paint() */ /*! \fn QRegion QDecoration::region(const QWidget *widget, int decorationRegion) \overload */ /*! \fn bool QDecoration::paint(QPainter *painter, const QWidget *widget, int decorationRegion, DecorationState state) Implement this function to paint the border and title decoration for the specified top level \a widget using the given \a painter and decoration \a state. The specified \a decorationRegion is a bitmask of the values described by the DecorationRegion enum. Note that \l{Qt for Embedded Linux} expects this function to return true if any of the widget's decorations are repainted; otherwise it should return false. \sa region() */ /*! \fn int QDecoration::regionAt(const QWidget *widget, const QPoint &point) Returns the type of the first region of the specified top level \a widget containing the given \a point. The return value is one of the DecorationRegion enum's values. Use the region() function to retrieve the actual region. If none of the widget's regions contain the point, this function returns \l None. \sa region() */ int QDecoration::regionAt(const QWidget *w, const QPoint &point) { int regions[] = { TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight, // Borders first Menu, Title, Help, Minimize, Normalize, Maximize, Close, // then buttons None }; // char *regions_str[] = { // "TopLeft", "Top", "TopRight", "Left", "Right", "BottomLeft", "Bottom", "BottomRight", // "Menu", "Title", "Help", "Minimize", "Normalize", "Maximize", "Close", // "None" // }; // First check to see if within all regions at all QRegion reg = region(w, w->geometry(), All); if (!reg.contains(point)) { return None; } int i = 0; while (regions[i]) { reg = region(w, w->geometry(), regions[i]); if (reg.contains(point)) { // qDebug("In region %s", regions_str[i]); return regions[i]; } ++i; } return None; }
// Compute position for ORIGIN BoxPoint RegionGraphNode::originToPos(const BoxPoint& origin, const GraphGC& gc) const { return origin + region(gc).space() / 2; }
int main(int, char*[]) { // typedef itk::Image<itk::CovariantVector<int, 3>, 2> ImageType; typedef itk::Image<itk::CovariantVector<unsigned char, 3>, 2> ImageType; ImageType::PixelType red; red.Fill(0); red[0] = 255; ImageType::PixelType black; black.Fill(0); ImageType::PixelType white; white.Fill(255); ImageType::PixelType green; // Note this is not 255 because then the magnitude of red and green would be the same, // which makes debugging hard since the gradient of the magnitude image is used internally (in IntroducedEnergy). green.Fill(0); green[1] = 122; ImageType::PixelType blue; blue.Fill(0); blue[2] = 255; ImageType::Pointer image = ImageType::New(); itk::Index<2> imageCorner = {{0,0}}; itk::Size<2> imageSize = {{100,100}}; itk::ImageRegion<2> region(imageCorner,imageSize); image->SetRegions(region); image->Allocate(); Mask::Pointer mask = Mask::New(); mask->SetRegions(region); mask->Allocate(); itk::ImageRegionIteratorWithIndex<Mask> initializeMaskIterator(mask, mask->GetLargestPossibleRegion()); while(!initializeMaskIterator.IsAtEnd()) { if(initializeMaskIterator.GetIndex()[0] < 55) { initializeMaskIterator.Set(mask->GetHoleValue()); } else { initializeMaskIterator.Set(mask->GetValidValue()); } ++initializeMaskIterator; } ITKHelpers::WriteImage(mask.GetPointer(), "mask.png"); // Create a red image itk::ImageRegionIterator<ImageType> initializeIterator(image, image->GetLargestPossibleRegion()); while(!initializeIterator.IsAtEnd()) { initializeIterator.Set(red); ++initializeIterator; } // Setup source and target patch itk::Size<2> patchSize = {{10,10}}; itk::Index<2> sourceCorner = {{10,10}}; itk::ImageRegion<2> sourceRegion(sourceCorner, patchSize); itk::Index<2> targetCorner = {{50,50}}; itk::ImageRegion<2> targetRegion(targetCorner, patchSize); itk::Index<2> perfectSourceCorner = {{75,75}}; itk::ImageRegion<2> perfectSourceRegion(perfectSourceCorner, patchSize); // Make the source patch green itk::ImageRegionIterator<ImageType> sourceRegionIterator(image, sourceRegion); while(!sourceRegionIterator.IsAtEnd()) { sourceRegionIterator.Set(green); ++sourceRegionIterator; } ITKHelpers::WriteImage(image.GetPointer(), "image.png"); { ImageType::Pointer regionHighlightImage = ImageType::New(); ITKHelpers::DeepCopy(image.GetPointer(), regionHighlightImage.GetPointer()); ITKHelpers::OutlineRegion(regionHighlightImage.GetPointer(), sourceRegion, white); ITKHelpers::OutlineRegion(regionHighlightImage.GetPointer(), targetRegion, black); ITKHelpers::OutlineRegion(regionHighlightImage.GetPointer(), perfectSourceRegion, blue); ITKHelpers::WriteImage(regionHighlightImage.GetPointer(), "regions.png"); } IntroducedEnergy<ImageType> introducedEnergy; introducedEnergy.SetDebugImages(true); // Bad match { std::cout << "Bad match:" << std::endl; float patchBoundaryEnergy = introducedEnergy.ComputeIntroducedEnergyPatchBoundary(image, mask, sourceRegion, targetRegion); std::cout << "patchBoundaryEnergy: " << patchBoundaryEnergy << std::endl; float maskBoundaryEnergy = introducedEnergy.ComputeIntroducedEnergyMaskBoundary(image, mask, sourceRegion, targetRegion); std::cout << "maskBoundaryEnergy: " << maskBoundaryEnergy << std::endl; float totalEnergy = introducedEnergy.ComputeIntroducedEnergy(image, mask, sourceRegion, targetRegion); std::cout << "totalEnergy: " << totalEnergy << std::endl; } // Perfect match { std::cout << "Perfect match:" << std::endl; // IntroducedEnergy<ImageType> introducedEnergy; typedef IntroducedEnergy<ImageType> IntroducedEnergyType; float patchBoundaryEnergy = introducedEnergy.ComputeIntroducedEnergyPatchBoundary(image, mask, perfectSourceRegion, targetRegion); std::cout << "patchBoundaryEnergy: " << patchBoundaryEnergy << std::endl; float maskBoundaryEnergy = introducedEnergy.ComputeIntroducedEnergyMaskBoundary(image, mask, perfectSourceRegion, targetRegion); std::cout << "maskBoundaryEnergy: " << maskBoundaryEnergy << std::endl; float totalEnergy = introducedEnergy.ComputeIntroducedEnergy(image, mask, perfectSourceRegion, targetRegion); std::cout << "totalEnergy: " << totalEnergy << std::endl; } return EXIT_SUCCESS; }