物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

OpenCVのgpu::countNonZeroをgpu::Streamで高速化する

cv::gpu::countNonZerogpu::Streamで高速化したいという需要があったので、その解決策を書いておく。

opencvの2系のcountNonZeroはstreamを使うことが出来ない。そのため、非同期処理を行い高速化する際のボトルネックになる。cv::gpu::reduceは2次元画像を1次元に射影するための関数でstreamが使えるので、CV_REDUCE_SUMを使って射影した後、軽量化された1次元画像を非同期ダウンロードし、CPUで積算処理を行えばよい。行または列の合計値が255を超えた場合は完全に一致しないものの、ラフな値で良い場合はこの方法が適切である。

以下はサンプルコードでは、コアの部分だけ記述した。streamやgvec等を使いまわさないと初期化に時間がかかるので注意が必要。

cv::gpu::GpuMat gmat = cv::gpu::GpuMat(cv::Size(1920, 1080), CV_8UC1);
cout << cv::gpu::countNonZero(gmat) << endl; //streamが使えない

cv::gpu::GpuMat gvec;
cv::gpu::Stream stream;
cv::gpu::reduce(gmat, gvec, 1, CV_REDUCE_SUM, -1, stream); //行ごとに積算する場合
cv::Mat vec;
stream.enqueueDownload(gvec, vec);
cout << cv::sum(vec)[0] << endl;

C# でWindows 上のプログラムのリソースを監視する

C#で以下のリソースの監視をしたいという需要があったのでサンプルコードを公開する。

  • 使用メモリ量
  • ハンドル数
  • GDI オブジェクト数
  • User オブジェクト数
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("user32.dll")]
        private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags);
        const uint GR_GDIOBJECTS = 0;
        const uint GR_USEROBJECTS = 1;
        /// <summary>
        /// GDI オブジェクトの数を返す
        /// </summary>
        /// <returns></returns>
        public static uint GetGDIObjects()
        {
            return GetGuiResources(Process.GetCurrentProcess().Handle, GR_GDIOBJECTS);
        }
        /// <summary>
        /// User オブジェクトの数を返す
        /// </summary>
        /// <returns></returns>
        public static uint GetUserObjects()
        {
            return GetGuiResources(Process.GetCurrentProcess().Handle, GR_USEROBJECTS);
        }
        static void DisplayMemory()
        {
            Console.WriteLine("Total memory  : {0:###,###,###,##0} bytes", GC.GetTotalMemory(false));
            Console.WriteLine("Private bytes   {0:###,###,###,##0} bytes", Process.GetCurrentProcess().PrivateMemorySize64); //プライベート メモリの量
            Console.WriteLine("Handle   count: {0}", Process.GetCurrentProcess().HandleCount); // ハンドル数
            Console.WriteLine("GDI  obj count: {0}", GetGDIObjects());
            Console.WriteLine("User obj count: {0}", GetUserObjects());
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            for (int i = 0; i < 100; i++)
            {
                using (var p = new Process())
                {
                    p.StartInfo.FileName = "ipconfig";
                    p.Start();
                    p.WaitForExit();
                }
            }
            DisplayMemory();
            GC.Collect(); //ガーベッジ コレクションを行う
            GC.WaitForPendingFinalizers(); //ガーベッジ コレクションが終わるまで待つ
            DisplayMemory();
        }
    }
}

標準出力とタスクマネージャーはこんな感じ

f:id:onsanai:20161004160344p:plain:w600

参照

.net - Finding Memory leaks in C# - Stack Overflow

GDI object count - C# / C Sharp

Windows 10のアップデート後の不本意な再起動を止める方法

f:id:onsanai:20161001184332p:plain:w600

Windows Updateを生かしたまま、アップデート後の不本意な再起動を止める方法は存在しない。Pro版でも、Enterprise版でも。

なので、Windows Updateのサービスを止めるしかない。という結論にたどり着いた。

諦めよう、Microsoftが改心するまで。

blog.bagooon.com

2019年現在、この記述は無効です。

3Dの位置と角度を持った情報の2次元プロジェクションマップ

CERNが開発しているROOT (バージョン5)を用いた検出器内の飛跡を2次元プロジェクションに投影して描画する方法。 具体的には三次元情報を持つ飛跡を2次元に投影したい時に使う。

#include <vector>
#include <random>
#include <limits>
#include <TArrow.h>
#include <TGraph.h>
#include <TAxis.h>
#include <TCanvas.h>
#include <TPaveText.h>
class Track
{
public:
    double px, py, ax, ay;
};
int main()
{
    std::random_device rand;
    std::vector<Track> vtrack;

    double width = 10;
    double height = 10;

    TCanvas *c1 = new TCanvas("c1", "", 1000, 1000);
    
    for (int i = 0; i < 100; i++) {
        Track t;
        t.px = double(rand()) / std::numeric_limits<unsigned int>::max() * width;
        t.py = double(rand()) / std::numeric_limits<unsigned int>::max() * height;
        t.ax = double(rand()) / std::numeric_limits<unsigned int>::max() - 0.5;
        t.ay = double(rand()) / std::numeric_limits<unsigned int>::max() - 0.5;
        vtrack.emplace_back(t);
    }
    double extz = 2; //ファクター
    double arrowsize = 0.01;

    TGraph* dummy = new TGraph();
    dummy->SetPoint(0, 0, 0); //左下
    dummy->SetPoint(1, width , height ); //右下
    dummy->SetMarkerColor(0); //マーカー色は白に

    dummy->GetXaxis()->SetTitle("X");
    dummy->GetXaxis()->SetLabelSize(0.04);
    dummy->GetXaxis()->SetTitleSize(0.04);

    dummy->GetYaxis()->SetTitle("Y");
    dummy->GetYaxis()->SetLabelSize(0.04);
    dummy->GetYaxis()->SetTitleSize(0.04);

    dummy->SetTitle("Arrow");
    dummy->Draw("AP"); //軸とポイントを描画

    for (auto p : vtrack) {

        TArrow *arrow = new TArrow(p.px, p.py, p.px + (p.ax)*extz, p.py + (p.ay)*extz, arrowsize, ">");
        arrow->SetFillColor(kBlue);
        arrow->SetLineColor(kBlue);
        arrow->SetFillStyle(1001);
        arrow->SetLineWidth(1);
        arrow->SetLineStyle(1);
        arrow->Draw();
    }

    //リファレンスの矢印
    double ref_px = -width / 8, ref_py = -height / 8;
    {
        TArrow *arrow = new TArrow(ref_px, ref_py, ref_px + extz, ref_py, arrowsize, ">");
        arrow->SetFillColor(kRed);
        arrow->SetLineColor(kRed);
        arrow->SetFillStyle(1001);
        arrow->SetLineWidth(1);
        arrow->SetLineStyle(1);
        arrow->Draw();
    }
    {
        TArrow *arrow = new TArrow(ref_px, ref_py, ref_px, ref_py + extz, arrowsize, ">");
        arrow->SetFillColor(kRed);
        arrow->SetLineColor(kRed);
        arrow->SetFillStyle(1001);
        arrow->SetLineWidth(1);
        arrow->SetLineStyle(1);
        arrow->Draw();
    }
    //リファレンスの文字
    double text_px = -width / 10, text_py = -height / 10;
    {
        TPaveText *pt = new TPaveText(text_px, text_py, 0, text_py + height / 30, "br");
        pt->SetFillColor(0);
        pt->SetLineColor(0);
        pt->SetShadowColor(0);
        TText *text = pt->AddText("1.0 [rad]");
        pt->Draw();
    }

    c1->SaveAs("Arrow.pdf");

    return 0;
}

作った画像

f:id:onsanai:20160919174322p:plain

2個の数列(std::vector<int>とか)から重複とかを探す

2個の数列から重複等を探す方法を紹介する。Linuxのjoinコマンドを高速化する場合などに使える。

続きは 2個の自作クラスの配列(std::vector<MyClass>)から重複とかを探す - 物理の駅 Physics station by 現役研究者

#include <algorithm>に便利な関数が用意されている。 ソートして、重複を削除した後、set_intersection, set_union, set_differenceを使ってみよう。

参照

Tech Tips: 知ってると便利なSTL(10) set_intersection, set_union, set_difference

乱数発生器についてのコードを修正しました(2016/11/30)

list1 = {5,7,4,2,9}
list2 = {4,3,8,3,2}
↓ソート
list1 = {2,4,5,7,9}
list2 = {2,3,3,4,8}
↓重複を削除
list1 = {2,4,5,7,9}
list2 = {2,3,4,8}
↓比較
積集合 = {2,4}
和集合 = {2,3,4,5,7,8,9}
差集合1 = {5,7,9}
差集合2 = {3,8}
#include <random>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

void main()
{
    const int Ntrk = 10000000;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, Ntrk - 1);
    std::vector<unsigned int> list1, list2;

    for (int i = 0; i < Ntrk; ++i) {
        list1.emplace_back(dis(gen)); //乱数を作成
        list2.emplace_back(dis(gen)); //乱数を作成
    }

    std::sort(list1.begin(), list1.end()); //ソート
    std::sort(list2.begin(), list2.end()); //ソート

    std::cout << list1.size() << " -> ";
    //重複を削除
    list1.erase(std::unique(list1.begin(), list1.end()), list1.end());
    std::cout << list1.size() << std::endl;

    std::cout << list2.size() << " -> ";
    //重複を削除
    list2.erase(std::unique(list2.begin(), list2.end()), list2.end()); 
    std::cout << list2.size() << std::endl;

    std::vector<unsigned int> list_inter; 
    //list1とlist2の両方にある値 (積集合)
    std::set_intersection(list1.begin(), list1.end(), list2.begin(), list2.end(), std::back_inserter(list_inter));

    std::vector<unsigned int> list_union; 
    //list1かlist2のどちらかに存在する値(和集合)
    std::set_union(list1.begin(), list1.end(), list2.begin(), list2.end(), std::back_inserter(list_union));

    std::vector<unsigned int> list_dif1; 
    //list1にあってlist2にない値(差集合)
    std::set_difference(list1.begin(), list1.end(), list2.begin(), list2.end(), std::back_inserter(list_dif1));

    std::vector<unsigned int> list_dif2; 
    //list2にあってlist1にない値(差集合)
    std::set_difference(list2.begin(), list2.end(), list1.begin(), list1.end(), std::back_inserter(list_dif2));

    //結果の確認
    std::cout << "dif1 + dif2 + inter = union" << std::endl;
    printf_s("%u + %u + %u = %u\n", list_dif1.size(), list_dif2.size(), list_inter.size(), list_union.size());
}