Привязка данных WPF: позволить/запретить управление на основе содержания var?

Я использовал python с opencv.

Мой алгоритм выглядит следующим образом:

  1. Сначала он берет красный канал с изображения
  2. Применить пороговое значение (минимальное значение 200) к красному каналу
  3. Затем примените морфологический градиент, а затем выполните «закрытие» (расширение с последующей эрозией)
  4. Затем он находит контуры на плоскости и выбирает самый длинный контур.

The outcome:

Код:

import numpy as np
import cv2
import copy


def findTree(image,num):
    im = cv2.imread(image)
    im = cv2.resize(im, (400,250))
    gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
    imf = copy.deepcopy(im)

    b,g,r = cv2.split(im)
    minR = 200
    _,thresh = cv2.threshold(r,minR,255,0)
    kernel = np.ones((25,5))
    dst = cv2.morphologyEx(thresh, cv2.MORPH_GRADIENT, kernel)
    dst = cv2.morphologyEx(dst, cv2.MORPH_CLOSE, kernel)

    contours = cv2.findContours(dst,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[0]
    cv2.drawContours(im, contours,-1, (0,255,0), 1)

    maxI = 0
    for i in range(len(contours)):
        if len(contours[maxI]) < len(contours[i]):
            maxI = i

    img = copy.deepcopy(r)
    cv2.polylines(img,[contours[maxI]],True,(255,255,255),3)
    imf[:,:,2] = img

    cv2.imshow(str(num), imf)

def main():
    findTree('tree.jpg',1)
    findTree('tree2.jpg',2)
    findTree('tree3.jpg',3)
    findTree('tree4.jpg',4)
    findTree('tree5.jpg',5)
    findTree('tree6.jpg',6)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

Если я меняю ядро ​​с (25,5) на (10,5), я получаю больше результаты на всех деревьях, кроме нижнего левого, enter image description here

мой алгоритм предполагает, что на дереве есть огни, а в нижнем левом дереве на вершине меньше света, чем на других.

12
задан pb2q 3 January 2015 в 07:32
поделиться

2 ответа

Since you're probably looking to bind the IsEnabled property of the button based on a string, try making a converter for it.

Ie...


<StackPanel>
<StackPanel.Resources>
<local:SomeStringConverter mystringtoboolconverter />
</StackPanel.Resources>
<Button IsEnabled="{Binding ElementName=mytree, Path=SelectedItem.Header, Converter={StaticResource mystringtoboolconverter}}" />
<StackPanel>

and the converter:


[ValueConversion(typeof(string), typeof(bool))]
    class SomeStringConverter : IValueConverter {
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
            string myheader = (string)value;
            if(myhead == "something"){
                return true;
            } else {
                return false;
            }
        }

        public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
            return null;
        }
    }

EDIT: Since the OP wanted to bind to a variable, something like this needs to be done:


public class SomeClass : INotifyPropertyChanged {
  private string _somestring;

  public string SomeString{
    get{return _somestring;}
    set{ _somestring = value; OnPropertyChanged("SomeString");}
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

}

Then, change the above binding expression to:

{Binding Path=SomeString, Converter={StaticResource mystringtoboolconverter}}

Note, you MUST implement INotifyPropertyChanged for your UI to be updated.

12
ответ дан 26 October 2019 в 10:46
поделиться

Do you have a ViewModel holding your string property set as the DataContext of the View where you try to do this Binding?

Then the following will work:

  // Example ViewModel
public class MyClass : INotifyPropertyChanged
{
    private string text;

    public string Text
    {
        get { return text; }
        set 
        { 
            text = value;
            UpdateProperty("Text");
            UpdateProperty("HasContent");
        }
    }

    public bool HasContent
    {
        get { return !string.IsNullOrEmpty(text); }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected void UpdateProperty(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

Then you should have done something like this in the code behind of the view:

this.DataContext = new MyClass();

And a Xaml example:

 <StackPanel>
        <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
        <Button IsEnabled="{Binding HasContent}">
            Click Me!
        </Button>
    </StackPanel>
7
ответ дан 26 October 2019 в 10:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: