示例#1
0
class EdgeSnapWindow(Window):
    def __init__(self):
        super(EdgeSnapWindow, self).__init__('Color Segmentation Example')
        self.image = Image("shapes.png", sample=True).edges()
        self.points = []

        self.show(self.image)

    def on_mouse(self, event, x, y, mouse_key, data=None):
        """ Callback for mouse events

            event - int - see cv2.EVENT_* constants
            x, y - int, int - position of the cursor
            mouse_key - int - mouse key
        """
        if event == cv2.EVENT_LBUTTONDOWN:
            self.points.append((x, y))

            self.image.clear_layers()
            for p in self.points:
                self.image.dl().circle(p, 5, color=Color.BLUE)

            features = self.image.edge_snap(self.points)

            for f in features:
                f.draw(color=Color.RED, width=2)

            self.show(self.image.apply_layers())

    def on_key(self, key):
        if key == 32:  # Space bar to clear points
            self.points = []
            self.image.clear_layers()
            self.show(self.image)
            print "Points cleared"
示例#2
0
class ColorSegmentationWindow(Window):

    def __init__(self):
        super(ColorSegmentationWindow, self).__init__('Color Segmentation Example')
        self.img = Image('simplecv')
        self.segmentation = ColorSegmentation()
        self.normal = True  # mode toggle for segment detection
        self.point1 = (0, 0)
        self.point2 = (0, 0)
        self.mosue_down = False

    def on_mouse(self, event, x, y, mouse_key, data=None):
        """ Callback for mouse events

            event - int - see cv2.EVENT_* constants
            x, y - int, int - position of the cursor
            mouse_key - int - mouse key
        """
        if event == cv2.EVENT_LBUTTONDOWN:
            self.point1 = (x, y)
            self.point2 = (x, y)
            self.mosue_down = True
        elif event == cv2.EVENT_MOUSEMOVE:
            if self.mosue_down == True:
                self.point2 = (x, y)
        elif event == cv2.EVENT_LBUTTONUP:
            self.mosue_down = False
            self.point2 = (x, y)

            x1, y1, w, h = points_to_roi(self.point1, self.point2)
            if w > 0 and h > 0:
                crop = self.img.crop(x1, y1, w, h)
                self.segmentation = ColorSegmentation()
                self.segmentation.add_to_model(crop)

    def on_key(self, key):
        if key == 32:  # Space bar to switch between modes
            self.normal = not self.normal
            print "Display Mode:", "Normal" if self.normal else "Segmented"

    def on_update(self):
        """ Callback for periodic update.
        """
        if self.normal:
            self.img.clear_layers()
            self.img.dl().rectangle_to_pts(self.point1, self.point2, color=Color.RED)
            self.show(self.img.apply_layers())
        else:
            self.segmentation.add_image(self.img)
            if self.segmentation.is_ready():
                img = self.segmentation.get_segmented_image()
                img = img.erode(iterations = 2).dilate().invert()
                self.show(img)
class EdgeSnapWindow(Window):

    def __init__(self):
        super(EdgeSnapWindow, self).__init__('Color Segmentation Example')
        self.image = Image("shapes.png", sample=True).edges()
        self.points = []

        self.show(self.image)

    def on_mouse(self, event, x, y, mouse_key, data=None):
        """ Callback for mouse events

            event - int - see cv2.EVENT_* constants
            x, y - int, int - position of the cursor
            mouse_key - int - mouse key
        """
        if event == cv2.EVENT_LBUTTONDOWN:
            self.points.append((x, y))

            self.image.clear_layers()
            for p in self.points:
                self.image.dl().circle(p, 5, color=Color.BLUE)

            features = self.image.edge_snap(self.points)

            for f in features:
                f.draw(color=Color.RED, width=2)

            self.show(self.image.apply_layers())

    def on_key(self, key):
        if key == 32:  # Space bar to clear points
            self.points = []
            self.image.clear_layers()
            self.show(self.image)
            print "Points cleared"
示例#4
0
# run through the list of pills (blobs) found and check their color and markup the image when they are found
for idx in range(len(packblobs)):
    pack = packblobs[idx].crop()

    pills_img = pack.hue_distance(pillcolor, minsaturation=saturation_threshold)
    pills_img = pills_img.binarize(127, inverted=True)

    pills = pills_img.find(Blob, minsize=pill_size)
    if not pills:
        continue

    for p in pills:
        p.image = pack
        p.convex_hull.draw(color=Color.RED, width=5)
    i.dl().blit(pack.apply_layers(), packblobs[idx].points[0])
    packblobs[idx].convex_hull.draw(color=Color.BLUE, width=5)

    pillcount = len(pills)
    if pillcount != expected_pillcount:
        print "pack at %d, %d had %d pills" % (packblobs[idx].x, packblobs[idx].y, pillcount)
        i.dl().text('ERROR', (packblobs[idx].x, packblobs[idx].y + 150), color=Color.RED)
        i.dl().text("Pills Found: " + str(pillcount),
                    (packblobs[idx].x, packblobs[idx].y + 170), color=Color.RED)
        i.dl().text("Pills Expected: " + str(expected_pillcount),
                    (packblobs[idx].x, packblobs[idx].y + 190), color=Color.RED)
    else:
        i.dl().text('OK', (packblobs[idx].x, packblobs[idx].y + 150), color=Color.GREEN)


# Continue to show the image
            example = 1
        else:
            example += 1
    else:
        threshold += threshold_step

    if example == 1:
        image = image.erode(threshold)
        text = "Erode Morphology Example: img.erode(" + str(threshold) + ")"

    elif example == 2:
        image = image.dilate(threshold)
        text = "Dilate Morphology Example: img.dilate(" + str(threshold) + ")"

    elif example == 3:
        image = image.morph_open()
        text = "Open Morphology Example: img.morph_open()"

    elif example == 4:
        image = image.morph_close()
        text = "Close Morphology Example: img.morph_close()"

    elif example == 5:
        image = image.morph_gradient()
        text = "Gradient Morphology Example: img.morph_gradient()"
    else:
        text = ''

    image.dl().text(text, (10, 10), color=Color.RED)
    image.show()
and put back into a display.
"""
print __doc__

import time
from simplecv.api import Color, Image


sleep_for = 3  # seconds to sleep for
text_point = (20, 20)
font_size = 24
draw_color = Color.YELLOW

while True:
    image = Image("orson_welles.jpg", sample=True)
    image.dl().set_font_size(font_size)
    image.dl().text("Original Size", text_point, color=draw_color)
    image.show()
    time.sleep(sleep_for)

    rot = image.rotate(45)
    rot.dl().set_font_size(font_size)
    rot.dl().text("Rotated 45 degrees", text_point, color=draw_color)
    rot.show()
    time.sleep(sleep_for)

    rot = image.rotate(45, scale=0.5)
    rot.dl().set_font_size(font_size)
    rot.dl().text("Rotated 45 degreesand scaled", text_point, color=draw_color)
    rot.show()
    time.sleep(sleep_for)
示例#7
0
# run through the list of pills (blobs) found and check their color and markup the image when they are found
for idx in range(len(packblobs)):
    pack = packblobs[idx].crop()

    pills_img = pack.hue_distance(pillcolor,
                                  minsaturation=saturation_threshold)
    pills_img = pills_img.binarize(127, inverted=True)

    pills = pills_img.find(Blob, minsize=pill_size)
    if not pills:
        continue

    for p in pills:
        p.image = pack
        p.convex_hull.draw(color=Color.RED, width=5)
    i.dl().blit(pack.apply_layers(), packblobs[idx].points[0])
    packblobs[idx].convex_hull.draw(color=Color.BLUE, width=5)

    pillcount = len(pills)
    if pillcount != expected_pillcount:
        print "pack at %d, %d had %d pills" % (packblobs[idx].x,
                                               packblobs[idx].y, pillcount)
        i.dl().text('ERROR', (packblobs[idx].x, packblobs[idx].y + 150),
                    color=Color.RED)
        i.dl().text("Pills Found: " + str(pillcount),
                    (packblobs[idx].x, packblobs[idx].y + 170),
                    color=Color.RED)
        i.dl().text("Pills Expected: " + str(expected_pillcount),
                    (packblobs[idx].x, packblobs[idx].y + 190),
                    color=Color.RED)
    else:
            example = 1
        else:
            example += 1
    else:
        threshold += threshold_step

    if example == 1:
        image = image.erode(threshold)
        text = "Erode Morphology Example: img.erode(" + str(threshold) + ")"

    elif example == 2:
        image = image.dilate(threshold)
        text = "Dilate Morphology Example: img.dilate(" + str(threshold) + ")"

    elif example == 3:
        image = image.morph_open()
        text = "Open Morphology Example: img.morph_open()"

    elif example == 4:
        image = image.morph_close()
        text = "Close Morphology Example: img.morph_close()"

    elif example == 5:
        image = image.morph_gradient()
        text = "Gradient Morphology Example: img.morph_gradient()"
    else:
        text = ''

    image.dl().text(text, (10, 10), color=Color.RED)
    image.show()
to think of this is if you played the card matching game, the cards would
pretty much have to be identical.  The template method doesn't allow much
for the scale to change, nor for rotation.  This is the most basic pattern
matching SimpleCV offers.  If you are looking for something more complex
you will probably want to look into img.find()
"""
print __doc__

import time

from simplecv.api import Image, Color, TemplateMatch

source = Image("templatetest.png", sample=True)  # the image to search
template = Image("template.png",
                 sample=True)  # the template to search the image for
t = 5

methods = [
    "SQR_DIFF", "SQR_DIFF_NORM", "CCOEFF", "CCOEFF_NORM", "CCORR", "CCORR_NORM"
]  # the various types of template matching available

for m in methods:
    img = Image("templatetest.png", sample=True)
    img.dl().text("current method: {}".format(m), (10, 20), color=Color.RED)
    fs = source.find(TemplateMatch, template, threshold=t, method=m)
    for match in fs:
        img.dl().rectangle((match.x, match.y), (match.width, match.height),
                           color=Color.RED)
    img.apply_layers().show()
    time.sleep(3)
img = Image('coins.jpg', sample=True)
coins = img.invert().find(Blob, minsize=200)

# Here we compute the scale factor
if coins:
    c = coins[-1]
    diameter = c.radius * 2
    size_ratio = quarter_size / diameter

# Now we print the measurements back on the picture
for coin in coins:
    # get the physical size of the coin
    size = (coin.radius * 2) * size_ratio
    # label the coin accordingly
    if 18 < size < 20:
        coin_type = "penny"
    elif 20 < size < 23:
        coin_type = "nickel"
    elif 16 < size < 18:
        coin_type = "dime"
    elif 23 < size < 26:
        coin_type = "quarter"
    else:
        coin_type = "unknown"

    text = "Type: {}, Size: {}mm".format(coin_type, size)
    img.dl().text(text, (coin.x + 45, coin.y + 45), color=Color.BLUE)

img.show()
time.sleep(10)
"""
This example uses the built in template matching.  The easiest way
to think of this is if you played the card matching game, the cards would
pretty much have to be identical.  The template method doesn't allow much
for the scale to change, nor for rotation.  This is the most basic pattern
matching SimpleCV offers.  If you are looking for something more complex
you will probably want to look into img.find()
"""
print __doc__

import time

from simplecv.api import Image, Color, TemplateMatch


source = Image("templatetest.png", sample=True) # the image to search
template = Image("template.png", sample=True) # the template to search the image for
t = 5

methods = ["SQR_DIFF", "SQR_DIFF_NORM", "CCOEFF",
           "CCOEFF_NORM", "CCORR", "CCORR_NORM"]  # the various types of template matching available

for m in methods:
    img = Image("templatetest.png", sample=True)
    img.dl().text("current method: {}".format(m), (10, 20), color=Color.RED)
    fs = source.find(TemplateMatch, template, threshold=t, method=m)
    for match in fs:
        img.dl().rectangle((match.x, match.y), (match.width, match.height), color=Color.RED)
    img.apply_layers().show()
    time.sleep(3)
img = Image('coins.jpg', sample=True)
coins = img.invert().find(Blob, minsize=200)

# Here we compute the scale factor
if coins:
    c = coins[-1]
    diameter = c.radius * 2
    size_ratio = quarter_size / diameter

# Now we print the measurements back on the picture
for coin in coins:
    # get the physical size of the coin
    size = (coin.radius * 2) * size_ratio
    # label the coin accordingly
    if 18 < size < 20:
        coin_type = "penny"
    elif 20 < size < 23:
        coin_type = "nickel"
    elif 16 < size < 18:
        coin_type = "dime"
    elif 23 < size < 26:
        coin_type = "quarter"
    else:
        coin_type = "unknown"

    text = "Type: {}, Size: {}mm".format(coin_type, size)
    img.dl().text(text, (coin.x + 45, coin.y + 45), color=Color.BLUE)

img.show()
time.sleep(10)