<jupyter_start><jupyter_text>Seminar 1<jupyter_code>import cv2 as cv
import numpy as np
img =cv.imread("photomode_01012021_191221.png")
img =cv.resize(img, (400,400))
img2 =cv.imread("photomode_01012021_191221.png", 0)
img2 =cv.resize(img2, (400,400))
cv.imshow("Pic", img)
cv.imshow("Pict", img2)
cv.waitKey(0)
cv.destroyAllWindows()
x =int(input())
counter = 0
counter2 = 0
for i in img.reshape(-1):
    counter2+=1
    if i < x:
        counter+=1
print(counter)
print(counter2)
print(counter/counter2)
img = cv.imread("cat.png")
img =cv.resize(img, (400,400))
img2 = cv.imread("cat.png")
img2 =cv.resize(img2, (400,400))
# left eye
start_point = (110, 200)
end_point = (170, 250)
color=(255, 0, 0)
thickness = 2
img2 = cv.rectangle(img2, start_point, end_point, color, thickness)
# right eye
start_point = (230, 200)
end_point = (290, 250)
color=(255, 0, 0)
thickness = 2
img2 = cv.rectangle(img2, start_point, end_point, color, thickness)
# nose
center_coordinates = (200, 300)
radius = 28
color=(0, 255, 0)
img2 = cv.circle(img2, center_coordinates, radius, color, thickness)
# left ear
# Polygon corner points coordinates
pts = np.array([[25, 70], [40, 160], 
                [115, 80], [50, 30], 
                ],
               np.int32)
  
pts = pts.reshape((-1, 1, 2))
  
isClosed = True
  
# Blue color in BGR
color = (0, 0, 255)
  
# Line thickness of 2 px
thickness = 2
  
# Using cv2.polylines() method
# Draw a Blue polygon with 
# thickness of 1 px
img2 = cv.polylines(img2, [pts], 
                      isClosed, color, thickness)
# Ellipse one
radius = 100
center = (370, 90)
axes = (radius, radius)
angle = 0
startAngle = 100
endAngle = 180
img2 = cv.ellipse(img2, center, axes, angle, startAngle, endAngle, (100, 0, 100), 2)
# Ellipse two
radius = 95
center = (365, 115)
axes = (radius, radius)
angle = 90
startAngle = 100
endAngle = 180
img2 = cv.ellipse(img2, center, axes, angle, startAngle, endAngle, (100, 0, 100), 2)
# Ellipse two
radius = 50
center = (330, 70)
axes = (radius, radius)
angle = 180
startAngle = 100
endAngle = 180
img2 = cv.ellipse(img2, center, axes, angle, startAngle, endAngle, (100, 0, 100), 2)
# Ellipse two
radius = 50
center = (330, 40)
axes = (3*radius, radius)
angle = 270
startAngle = 100
endAngle = 168
img2 = cv.ellipse(img2, center, axes, angle, startAngle, endAngle, (100, 0, 100), 2)
cv.imshow("Pic", img2)
cv.waitKey(0)
cv.destroyAllWindows()
cv.imwrite("file.jpg", img)
cv.imwrite("file2.jpg", img2)<jupyter_output><empty_output><jupyter_text>Seminar 2  Task 3<jupyter_code>import cv2 as cv
img = cv.imread("Task3.PNG")
img2 = cv.imread("Task3.PNG", 0)
cv.imshow("Pic", img)
cv.waitKey(0)
cv.destroyAllWindows()
cv.imshow("Pic2", img2)
cv.waitKey(0)
cv.destroyAllWindows()
img2 =cv.adaptiveThreshold(img2, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 27, 4)
cv.imshow("Pic", img)
cv.imshow("Pic2", img2)
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task 4<jupyter_code>import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import matplotlib
def adjust_gamma(image, gamma=1.0):
	# build a lookup table mapping the pixel values [0, 255] to
	# their adjusted gamma values
	invGamma = 1.0 / gamma
	table = np.array([((i / 255.0) ** invGamma) * 255
		for i in np.arange(0, 256)]).astype("uint8")
	# apply gamma correction using the lookup table
	return cv.LUT(image, table)
img = cv.imread("Task5.png")
gamma = 0
alpha = int(0)
beta = int(0)
def plotHist(img, dst):
    hist, bins = np.histogram(img.ravel(), 256, [0, 256])
    hist = hist / hist.max() * 200
    stack = np.vstack((np.linspace(0, 256, 256), hist.reshape(-1))).T
    stack[:, 1] = dst.shape[0] - stack[:, 1]
    cv.polylines(dst, [np.int32(stack)], True, (0, 255, 255))
def gamma_alpha_beta():
    img2 = img
    #img2 = adjust_gamma(img, gamma)
    #img2 = cv.convertScaleAbs(img2, alpha = alpha, beta = beta)
    histogram = np.zeros((200, 256, 3), np.uint8)
    imgGray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
    plotHist(imgGray, histogram)
    imgGray = cv.equalizeHist(imgGray)
    histogram_eq = np.zeros((200, 256, 3), np.uint8)
    plotHist(imgGray, histogram_eq)
    cv.imshow("Pic", img2)
    cv.imshow("equalized", imgGray)
    cv.imshow("Hist", histogram)
    cv.imshow("equalizedHist", histogram_eq)
def gammaf(val):
    global gamma 
    gamma = val/128
    gamma_alpha_beta()
    
def alphaf(val):
    global alpha 
    alpha= val
    gamma_alpha_beta()
    
def betaf(val):
    global beta 
    beta = val
    gamma_alpha_beta()
cv.imshow("Pic", img)
cv.createTrackbar('gamma', "Pic", 0, 255, gammaf)
cv.createTrackbar('alpha', "Pic", 0, 255, alphaf)
cv.createTrackbar('beta', "Pic", 0, 255, betaf)
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task5<jupyter_code>import numpy as np
import cv2 as cv
import os
import random
img = cv.imread("Task5.png")
img2 = cv.imread("Task5.png")
noise = 50#int(float(input()))
pic_number = 10
img = np.float64(img)
noise_pic = np.copy(img)
a = list()
for k in range(pic_number):
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            noise_val = random.randint(-noise, noise)
            noise_pic[i][j] = img[i][j] + noise_val
    a.append(np.copy(noise_pic))
result = np.asarray([np.add.reduce(i) for i in zip(*a)])
result = np.uint8(np.clip(result/pic_number, 0, 255))

cv.imshow("Noise", np.uint8(np.clip(a[0], 0, 255)))
cv.imshow("Pic", result)
cv.imshow("Pic2", img2)
cv.waitKey(0)
cv.destroyAllWindows()
for i in range(pic_number):
    cv.imshow("Pic" + str(i), np.uint8(np.clip(a[i], 0, 255)))
cv.waitKey(0)
cv.destroyAllWindows()
for i in range(5):
    print(a[i][50][50])
print(result[50][50])
print(img[50][50])<jupyter_output>[55 55 55]
[54 54 54]
[46 46 46]
[51 51 51]
[48 48 48]
[47 47 47]
[39 39 39]<jupyter_text>Task 6  Инициализация<jupyter_code>import numpy as np
import cv2 as cv
import os
import random
max_lowThreshold = 100
title_trackbar_1 = 'Min Threshold:'
title_trackbar_2 = 'Max Threshold:'
ratio = 3
kernel_size = 3
# colors
red_color = (0, 0, 255)
green_color = (0, 255, 0)
orange_color = (0, 128, 255)
purple_color = (157,0, 90)
blue_color = (255, 0, 0)
magenta_color = (255, 0, 255)
# bar variable 
low_threshold = 100
max_threshold = 100

max_level_contour = 0
treshold_filter_level = 0
exercise = 0
img = cv.imread("task6-test.jpg")
img = cv.resize(img, (600, 600))
def task_six_zero_clear():
    return img.copy()<jupyter_output><empty_output><jupyter_text>Задание 6-0 Реализовать функцию фильтра Кенни<jupyter_code>def CannyFilter(img, low_threshold, max_threshold):
    img_blur = cv.blur(img, (3,3))
    detected_edges = cv.Canny(img_blur, low_threshold, max_threshold, kernel_size)
    mask = detected_edges != 0
    canny_result = img * (mask[:,:,None].astype(img.dtype))
    return detected_edges, canny_result

def task_six_zero_Canny(dst):
    return dst.copy()<jupyter_output><empty_output><jupyter_text>Задание 6-1 Написать программу, выделяющую границы объектов методом КэнниРеализовать выделение контуров объектов по изображению границ,полученному методом Кэнни для произвольного изображения, а также ихвизуализацию поверх исходного изображения.• Детектор границ Кэнни (cv::Canny)• Обнаружение и отрисовка контуров (cv:: findContours, cv::drawContours)<jupyter_code>def task_six_one(img2, contours, hierarchy):
    cv.drawContours(img2, contours, -1, (0,255,0), 3, cv.LINE_AA, hierarchy, 1)
    for c in contours:
        x, y, w, h = cv.boundingRect(c)
        rect_color = green_color
        cv.rectangle(img2, (x, y), (x + w, y + h), rect_color, 1)
    return img2<jupyter_output><empty_output><jupyter_text>Задание 6.2 Написать программу, которая автоматически определяет для одного объекта, выделенного методом Кэнни размер объекта (маленький, средний, большой) относительно общего размера изображенияВыставлены ограничения при которых если площадь больше 5% - окрас квадрата зелёный, иначе если больше 3%(от 3% до 5%) - окрас оранжевый, иначе (от 0% до 3%) - окрас красный.<jupyter_code>def task_six_two(img2, contours):
    x_img = img.shape[0]
    y_img = img.shape[1]
    square_img_s = x_img * y_img 
    for c in contours:
        x, y, w, h = cv.boundingRect(c)
        rect_color = red_color
        rect_size = w * h
        if rect_size >= (square_img_s / 20.):
            rect_color = green_color
        elif rect_size >= (square_img_s / 30.):
            rect_color = orange_color
        else:
            rect_color = red_color
        cv.rectangle(img2, (x, y), (x + w, y + h), rect_color, 1)
    return img2<jupyter_output><empty_output><jupyter_text>Задание 6.3  Написать программу, которая автоматически определяет для одного объекта, выделенного методом Кэнни форму объекта (кравдрат, прямоугольник, треугольник, круг, овал)Написана функция, которая возвращает имя найденной фигуры. Каждая фигура обводится своим цветом:Квадрат - зелёным;Прямоугольник - оранжевым;Треугольник - красным;Круг - фиолетовым;Овал - синим;Пятиугольник - маджента;Шестиугольник - белым.<jupyter_code>#Return approximated contour
def approximate_contour(contour):
    epsilon  =  0.02 * cv.arcLength(contour, True)
    approximate = cv.approxPolyDP(contour, epsilon, True)
    return approximate

#Return length of vector
def vector_len(v):
    v = np.reshape(v, -1)
    return np.sqrt(v[0] ** 2 + v[1] ** 2)

#Return difference between two vectors
def diff(x, y):
    x = x.ravel()
    y = y.ravel()
    return [x[0] - y[0], x[1] - y[1]]

#Return the name of the shape
def find_shape(contour):
    approximate = approximate_contour(contour)
    if len(approximate) == 3:
        shape = "triangle"
    elif len(approximate) == 4:
        (x, y, w, h) = cv.boundingRect(approximate)
        figure_area = cv.contourArea(approximate)
        approximate_area = vector_len(diff(approximate[0], approximate[1])) ** 2
        area = figure_area / approximate_area
        #Give small window for error
        shape = "square" if 0.9 <= area <= 1.2 else "rectangle"
    elif len(approximate) == 5:
        shape = "pentagon"
    elif len(approximate) == 6:
        shape = "hexagon"
    else:
        M = cv.moments(approximate)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        radius = vector_len(approximate[0] - (cX, cY))
        approximate_area = np.pi * (radius ** 2)
        figure_area = cv.contourArea(approximate)
        area = approximate_area / figure_area
        if 0.9 <= area <= 1.2:
            shape = "circle"
        else:
            shape = "ellipse"
    return shape

def task_six_three(img2, contours):
    for c in contours:
        x, y, w, h = cv.boundingRect(c)
        rect_name = find_shape(c)
        rect_color = (0,0,0)
        if rect_name == "square":
            rect_color = green_color
        elif rect_name == "rectangle":
            rect_color = orange_color
        elif rect_name == "triangle":
            rect_color = red_color
        elif rect_name == "circle":
            rect_color = purple_color
        elif rect_name == "ellipse":
            rect_color = blue_color
        elif rect_name == "pentagon":
            rect_color = magenta_color
        elif rect_name == "hexagon":
            rect_color = (255, 255, 255)
        cv.rectangle(img2, (x, y), (x + w, y + h), rect_color, 1)
    return img2<jupyter_output><empty_output><jupyter_text>GUI<jupyter_code># Cutting contours noise
def approx_contour(contour):
    epsilon = cv.arcLength(contour, True)
    approx = cv.approxPolyDP(contour, 0.02 * epsilon, True)
    return approx

def filter_contours(contours, tresh):
    filtered = []
    approxes = []
    for c in contours:
        hull = cv.convexHull(c)

        area = cv.contourArea(hull)
        approx = approx_contour(c)
        if area > tresh:
            filtered.append(c)
            approxes.append(approx)
    return filtered, approxes

def update():
    global img
    global low_threshold 
    global max_threshold
    global treshold_filter_level
    detected_edges, dst = CannyFilter(img, low_threshold, max_threshold)
    contours, hierarchy = cv.findContours(detected_edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    img2 = dst.copy()
    contours, approx = filter_contours(contours, tresh = treshold_filter_level)
    t_contour = np.vstack(contours)
    conv_hull = cv.convexHull(t_contour)
    if exercise == 0:
        img2 = task_six_zero_clear()
    elif exercise == 1:
        img2 = task_six_zero_Canny(dst)
    elif exercise == 2:
        img2 = task_six_one(img2, contours, hierarchy)
    elif exercise == 3: 
        img2 = task_six_two(img2, conv_hull)
    elif exercise == 4:
        img2 = task_six_three(img2, contours)
    cv.imshow("Pic", img2)

def CannyThresholdMin(val):
    global low_threshold 
    low_threshold = val
    update()

def CannyThresholdMax(val):
    global max_threshold
    max_threshold = val
    update()

def TresholdFilterLevel(val):
    global treshold_filter_level
    treshold_filter_level = val
    update()

def exercise_f(val):
    global exercise
    exercise = val
    update()
#Автоматическое определение
cv.imshow("Pic", img)
cv.createTrackbar(title_trackbar_1, "Pic" , 190, max_lowThreshold*8, CannyThresholdMin)
cv.createTrackbar(title_trackbar_2, "Pic" , 230, max_lowThreshold*8, CannyThresholdMax)
cv.createTrackbar("TresholdFilterLevel", "Pic" , 45, max_lowThreshold*6, TresholdFilterLevel)
cv.createTrackbar("Task type", "Pic" , 1, 4, exercise_f)
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Changed prog<jupyter_code>import cv2 as cv
import numpy as np
from imutils import contours
def scaleImg(image, scale: float):
    width, height = image.shape[1], image.shape[0]
    return cv.resize(image, (int(width * scale), int(height * scale)))

def clipImg(image, max_size, filter=cv.INTER_CUBIC):
    width, height = image.shape[1], image.shape[0]
    max_dim = max(width, height)
    ratio = float(max_size) / max_dim
    return cv.resize(image, (int(width*ratio), int(height*ratio)), interpolation=filter)
treshold1 = 100
treshold2 = 100
x_pos = 1
y_pos = 1
mode = 0
modes_count = 2
orig_img = cv.imread('task6-3.PNG')
#'task6-3.PNG'
#'task6-test2.jpg'
img = np.copy(orig_img)
img = clipImg(img, 600)
total_area = img.shape[0] * img.shape[1]
font = cv.FONT_HERSHEY_SIMPLEX
fontScale = 1
fontColor = (0, 255, 0)
thickness = 1
controlls_window_name = 'controlls'
edges_window_name = 'edges'

#cv.namedWindow(controlls_window_name)
cv.namedWindow(edges_window_name)

def pass_callback(x):
    pass

def set_treshold1(x):
    global treshold1
    treshold1 = x

def set_treshold2(x):
    global treshold2
    treshold2 = x

def nextMode(x):
    global mode
    mode = (mode + x) % modes_count
cv.namedWindow('original image')
cv.createTrackbar('treshold 1', 'original image', treshold1, 800, set_treshold1)
cv.createTrackbar('treshold 2', 'original image', treshold2, 800, set_treshold2)

canvas = np.zeros(img.shape, dtype=np.uint8)
overlay = np.zeros(img.shape, dtype=np.uint8)
approx_cntrs = np.zeros(img.shape, dtype=np.uint8)

def draw_bounding_boxes(canvas):
    for c in contours:
        draw_countour_bounds(c, canvas)

def draw_countour_bounds(c, canvas, color=(0, 255, 0)):
    x, y, w, h = cv.boundingRect(c)
    cv.rectangle(canvas, (x, y), (x + w, y + h), color, 1)

def onMouse(event, x, y, flags, param):
    global x_pos, y_pos
    x = np.clip(x, 0, img.shape[1] - 1)
    y = np.clip(y, 0, img.shape[0] - 1)
    x_pos = x
    y_pos = y

cv.setMouseCallback(edges_window_name, onMouse)

def filter_contours(cntrs, tresh = 100):
    filtered = []
    approxes = []
    for c in cntrs:
        hull = cv.convexHull(c)

        area = cv.contourArea(hull)
        approx = approx_contour(c)
        if area > tresh:
            filtered.append(c)
            approxes.append(approx)
    return filtered, approxes

def approx_contour(cntr):
    perimeter = cv.arcLength(cntr, True)
    approx = cv.approxPolyDP(cntr, 0.02 * perimeter, True)
    return approx

def vect_len(v):
    v = np.reshape(v, -1)
    return np.sqrt(v[0] ** 2 + v[1] ** 2)

def getPt(x):
    x = np.reshape(x, -1)
    return [x[0], x[1]]

def diff(x, y):
    x = x.ravel()
    y = y.ravel()
    return [x[0] - y[0], x[1] - y[1]]

def classify_shape(cntr, approximate):
    if len(approximate) == 3:
        shape = "triangle"
    elif len(approximate) == 4:
        (x, y, w, h) = cv.boundingRect(approximate)
        fig_area = cv.contourArea(approximate)
        approx_area = vect_len(diff(approximate[0], approximate[1])) ** 2
        ar = fig_area / approx_area
        shape = "square" if 0.9 <= ar <= 1.2 else "rectangle"
    elif len(approximate) == 5:
        shape = "pentagon"
    elif len(approximate) == 6:
        shape = "hexagon"
    else:
        M = cv.moments(approximate)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        radius = vect_len(approximate[0] - (cX, cY))
        approx_area = np.pi * (radius ** 2)
        fig_area = cv.contourArea(approximate)
        ar = approx_area / fig_area
        if 0.9 <= ar <= 1.2:
            shape = "circle"
        elif 0.5 <= ar <= 2.0:
            shape = "ellipse"
        else:
            shape = "ellipse"
    return shape

while True:
    blurred = cv.blur(img, (3, 3))
    edges_canny = cv.Canny(blurred, treshold1, treshold2)
    contours, hierarchy = cv.findContours(edges_canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    contours, approxs = filter_contours(contours)
    canvas[:, :, :] = 0
    overlay[:, :, :] = 0
    approx_cntrs[:, :, :] = 0
    draw_bounding_boxes(canvas)
    cv.drawContours(overlay, contours, -1, (50, 255, 0), 2)
    cv.drawContours(approx_cntrs, approxs, -1, (0, 20, 255), 2)
    for idx, c in enumerate(contours):
        x, y, w, h = cv.boundingRect(c)
        # point in bounding box
        result = x <= x_pos <= x + w and y <= y_pos <= y + h
        if result:
            hull = cv.convexHull(c)
            cv.drawContours(approx_cntrs, [hull], 0, (255,10,10))
            area = cv.contourArea(hull)
            fig_type = 'shit'
            try:
                fig_type = classify_shape(c, approxs[idx])
            except:
                pass
            draw_countour_bounds(c, canvas, (244, 0, 0))
            area_ratio = area * 100 / total_area
            cv.putText(canvas, 'area: ' + "{:.1f}".format(area_ratio) + '%', (np.int32(x), np.int32(y + 15)), font, 0.8, fontColor, thickness)
            size_label = 'small'
            if area_ratio < 1:
                size_label = 'small'
            elif area_ratio < 5:
                size_label = 'medium'
            else:
                size_label = 'large'
            cv.putText(canvas, size_label, (np.int32(x), np.int32(y + 35)), font, 0.8, fontColor, thickness) # (np.int32(x + w / 2 - 40), np.int32(y + h / 2) + 15), font, 0.8, fontColor, thickness)
            cv.putText(canvas, 'type: ' + fig_type, (np.int32(x), np.int32(y + 55)), font, 0.8, fontColor, thickness)
    #cv.imshow('image', cv.add(img, overlay))
    cv.imshow('original image', orig_img)
    
    cv.imshow('Approximated contour', approx_cntrs)
    result = canvas
    if mode == 0:
        result = cv.add(cv.cvtColor(edges_canny, cv.COLOR_GRAY2BGR), canvas)
    else:
        result = cv.cvtColor(edges_canny, cv.COLOR_GRAY2BGR)

    cv.imshow(edges_window_name, result)

    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
cv.destroyAllWindows()
cv.namedWindow('img')
grades = [0.7, 0.3]
width = img.shape[1]
height = img.shape[0]

def approx_contour(cntr):
    epsilon = cv.arcLength(cntr, True)
    approx = cv.approxPolyDP(cntr, 0.02 * epsilon, True)
    return approx

def filter_contours(cntrs, tresh=0.002):
    global area_ratio
    filtered = []
    approximate_cntrs = []
    for c in cntrs:
        hull = cv.convexHull(c)
        area = cv.contourArea(hull)
        approx = approx_contour(c)
        if area / total_area > tresh:
            filtered.append(c)
            approximate_cntrs.append(approx)
    return filtered, approximate_cntrs


def classify_area(cntr):
    global total_area, grades, width, height
    x, y, w, h = cv.boundingRect(hull)
    area = cv.contourArea(cntr)
    min_dim = min(width, height)
    max_ext = max(w, h)
    ratio = max_ext/min_dim
    if max_ext/min_dim >= grades[0]:
        return ratio, 'large'
    elif max_ext/min_dim >= grades[1]:
        return ratio, 'medium'
    else:
        return ratio, 'small'

def getContours(img, t1, t2):
    blurred = cv.blur(img, (3, 3))
    edges_canny = cv.Canny(blurred, t1, t2)

    contours, hierarchy = cv.findContours(edges_canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    contours, approxs = filter_contours(contours)

    total_contour = np.vstack(contours)
    hull = cv.convexHull(total_contour)

    return hull, total_contour

max_ratio = -1
for i in range(10):
    for j in range(10):
        t1 = np.int0(i * 255 / 10)
        t2 = np.int0(j * 255 / 10)

        hull, total_contour = getContours(img, t1, t2)
        area_ratio, size_label = classify_area(hull)

        if area_ratio > max_ratio:
            max_ratio = area_ratio

            treshold1 = t1
            treshold2 = t2
mode = 0
modes_count = 2

def nextMode(x):
    global mode
    mode = (mode + x) % modes_count

def set_treshold1(x):
    global treshold1
    treshold1 = x

def set_treshold2(x):
    global treshold2
    treshold2 = x

cv.createTrackbar('treshold 1', 'img', treshold1, 800, set_treshold1)
cv.createTrackbar('treshold 2', 'img', treshold2, 800, set_treshold2)

canvas = np.zeros(img.shape, dtype=np.uint8)
overlay = np.zeros(img.shape, dtype=np.uint8)
approx_cntrs = np.zeros(img.shape, dtype=np.uint8)


def flatten(cntrs):
    list_of_pts = []
    for ctr in cntrs:
        list_of_pts += [pt[0] for pt in ctr]
    return np.asarray(list_of_pts)

while True:
    canvas[:, :, :] = 0
    overlay[:, :, :] = 0
    approx_cntrs[:, :, :] = 0

    hull, total_contour = getContours(img, treshold1, treshold2)

    area_ratio, size_label = classify_area(hull)

    if mode == 1:
        cv.drawContours(overlay, total_contour, -1, (50, 255, 0), 1)
    else:
        x, y, w, h = cv.boundingRect(hull)
        cv.putText(overlay, 'area: ' + "{:.1f}".format(area_ratio * 100) + '%',
                   (np.int32(x + w / 2 - 40), np.int32(y + h / 2)), font, 0.6, fontColor, thickness)
        cv.putText(overlay, size_label,
                   (np.int32(x + w / 2 - 40), np.int32(y + h / 2) + 15), font, 0.6, fontColor, thickness)

    cv.drawContours(overlay, [hull], 0, (255, 10, 10))

    cv.imshow('img', img)
    cv.imshow('overlay', cv.addWeighted(img, 0.3, overlay, 0.7, 0.0))

    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task 7<jupyter_code>import numpy as np
import cv2 as cv
import os
import random
img = cv.imread("Task5.png")
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)<jupyter_output><empty_output><jupyter_text>Задание 7 Продемонстрировать возможности линейной фильтрации изображений на основе: Гауссова фильтра, медианного, фильтра с произвольным ядром, оператора Собеля, фильтра Лапласа. Продемонстрировать удаление равномерного шума и Гауссова.• Гауссов(cv::blur) и медианный фильтр (cv::medianBlur).• Фильтрация произвольной маской (cv::filter2D).• Выделение границ объектов (cv::Sobel).• Фильтр Лапласа. Исследовать влияние входных параметров нарезультат фильтрации, провести сравнение с фильтром Собеля.• cv::randn – нормальное распределение, cv::randu – равномерноераспределение.<jupyter_code># Test of filters with kernel = 3
if False:
    cv.imshow("Pic", img)
    cv.imshow("Gauss", cv.blur(img.copy(), (3, 3)))
    kernel_size = 3
    kernel = np.ones((kernel_size, kernel_size), dtype = np.float32)
    kernel /= (kernel_size * kernel_size)
    cv.imshow("filter2D", cv.filter2D(img.copy(), cv.CV_8U, kernel))
    cv.imshow("Sobel", cv.Sobel(cv.blur(img, (3, 3)), cv.CV_64F, 1, 1, ksize = 3))
    cv.imshow("Laplacian", cv.Laplacian(cv.blur(img, (3, 3)), cv.CV_64F, ksize = 3))
    cv.waitKey(0)
    cv.destroyAllWindows()
def make_noise(img, noise_size, is_normal):
    noise = np.zeros(img.shape)
    if is_normal:
        cv.randn(noise, 0,  noise_size)
    else:
        cv.randu(noise, -noise_size, noise_size)
    return noise

def make_noise_img(img, noise_size, is_normal):
    return np.uint8(np.clip(cv.add(np.float64(img), \
        make_noise(img, noise_size, is_normal)), 0, 255)) # Translate img to float, add noise to img(too has float type), clip it to borders of uint8 and translate it to uint8 

def make_filtered_img(noise_img, filter_name, kernel_elem):
    if filter_name == "Origin":
        return img
    elif filter_name == "Gaussian":
        return cv.blur(noise_img, (kernel_elem, kernel_elem))
    elif filter_name == "Median":
        if kernel_elem % 2 != 1:
            kernel_elem += 1
        return cv.medianBlur(noise_img, kernel_elem) # Work only with kernel elem % 2 == 1
    elif filter_name == "Filter2D":
        return cv.filter2D(noise_img, cv.CV_8U, \
        np.ones((kernel_elem, kernel_elem), dtype = np.float64) / (kernel_elem * kernel_elem)) # Generating kernel that has sizes kernel_elem X kernel_elem and each element of this kernel is equal to 1.0 / kernel_elem
    elif filter_name == "Sobel":
        if kernel_elem % 2 != 1:
            kernel_elem += 1
        return cv.Sobel(cv.blur(noise_img, (kernel_elem, kernel_elem)), cv.CV_64F, 1, 1, ksize = kernel_elem) # Work only with kernel elem % 2 == 1
    elif filter_name == "Laplacian":
        if kernel_elem % 2 != 1:
            kernel_elem += 1
        return cv.Laplacian(cv.blur(img, (kernel_elem, kernel_elem)), cv.CV_64F, ksize=kernel_elem) # Work only with kernel elem % 2 == 1
    else:
        return None
def plotHist(img, hist_size = (200, 256, 3)):
    histogram = np.zeros(hist_size, np.uint8)
    hist, bins = np.histogram(img.ravel(), 256, [0, 256])
    hist = hist / hist.max() * 200
    stack = np.vstack((np.linspace(0, 256, 256), hist.reshape(-1))).T
    stack[:, 1] = histogram.shape[0] - stack[:, 1]
    cv.polylines(histogram, [np.int32(stack)], True, (0, 255, 255))
    return histogram
def concat_img_hist():
    return
#For trackbars
is_normal = True
noise_size = 40
kernel_size = 3
filter_names = list(("Origin", "Gaussian", "Median", "Filter2D", "Sobel", "Laplacian"))
filter_type = 0
# Images
noise_img = make_noise_img(img, 40, True)
filtered_img = make_filtered_img(noise_img, filter_names[filter_type], kernel_size)

def update():
    global filtered_img
    global histogram
    filtered_img = make_filtered_img(noise_img, filter_names[filter_type], kernel_size)
    cv.imshow("Histogram", plotHist(filtered_img))
    cv.imshow("Filtered Pic", filtered_img)
    cv.imshow("Noise Pic", noise_img)


def change_noise(val):
    global noise_img
    global noise_size
    noise_size = val
    noise_img = make_noise_img(img, noise_size, is_normal)
    update()


def change_is_normal(val):
    global noise_img
    if val == 1:
        is_normal = True
    else:
        is_normal = False
    noise_img = make_noise_img(img, noise_size, is_normal)
    update()


def change_kernel_size(val):
    global kernel_size
    global filtered_img
    if val > 0:
        kernel_size = val
        update()


def change_filter_type(val):
    global filtered_img
    global filter_type
    filter_type = val
    update()
#Original or filtered image
cv.imshow("Filtered Pic", img)
cv.createTrackbar("Type of Filter","Filtered Pic", 0, 5, change_filter_type)
cv.createTrackbar("Filters kernel size", "Filtered Pic", 3, 30, change_kernel_size)
#Hist of image
cv.imshow("Histogram", plotHist(filtered_img))
#Noise image
cv.imshow("Noise Pic", noise_img)
cv.createTrackbar("noise size", "Noise Pic", 40, 800, change_noise)
cv.createTrackbar("normal/uniform", "Noise Pic", 1, 1, change_is_normal)
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task 8  Initialization<jupyter_code>import numpy as np
import cv2 as cv
import os
import random<jupyter_output><empty_output><jupyter_text>Задание 8 Реализовать поиск линий либо окружностей (на выбор) на характерных изображениях, исследовать эффективность при различных параметрах.<jupyter_code>img = cv.imread('Task-8.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
rho_size = 1.0
theta_devide_size = 360
hough_treshold = 200
low_threshold = 50
high_threshold = 150
aperture_size = 3
def update():
    edges = cv.Canny(gray, low_threshold, high_threshold, \
        apertureSize = aperture_size) # work only with 3 or 5
    lines = cv.HoughLinesP(edges, rho_size, np.pi / theta_devide_size, hough_treshold, \
        minLineLength = 10, maxLineGap = 10)
    #lines = cv.HoughLines(edges, rho_size, np.pi / theta_devide_size, hough_treshold)
    res = img.copy()
    for line in lines:
        #rho,theta = line[0]
        #a = np.cos(theta)
        #b = np.sin(theta)
        #x0 = a * rho
        #y0 = b * rho
        ## x1 stores the rounded off value of (r * cos(theta) - 1000 * sin(theta))
        #x1 = int(x0 + 1000 * (-b))
        ## y1 stores the rounded off value of (r * sin(theta)+ 1000 * cos(theta))
        #y1 = int(y0 + 1000 * (a))
        ## x2 stores the rounded off value of (r * cos(theta)+ 1000 * sin(theta))
        #x2 = int(x0 - 1000 * (-b))
        ## y2 stores the rounded off value of (r * sin(theta)- 1000 * cos(theta))
        #y2 = int(y0 - 1000 * (a))
        x1, y1, x2, y2 = line[0]
        cv.line(res, (x1, y1), (x2, y2), (0, 0, 255), 2)
    cv.imshow('image', res)

def change_rho_size(val):
    global rho_size
    if val > 0:
        rho_size = val / 100
        update()


def change_theta_size(val):
    global theta_devide_size
    if val > 0 :
        theta_devide_size = val
        update()


def change_hough_treshold(val):
    global hough_treshold
    hough_treshold = val
    update()


def change_low_treshold(val):
    global low_threshold
    low_threshold = val
    update()


def change_high_threshold(val):
    global high_threshold
    high_threshold = val
    update()
cv.imshow('image', img)
cv.createTrackbar('rho', 'image', 100, 1000, change_rho_size)
cv.createTrackbar('theta', 'image', 360, 360, change_theta_size)
cv.createTrackbar('hough treshold', 'image', 100, 500, change_hough_treshold)
cv.createTrackbar('low treshold', 'image', 50, 500, change_low_treshold)
cv.createTrackbar('high threshold', 'image', 150, 500, change_high_threshold)
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task 9<jupyter_code>import numpy as np
import cv2 as cv
import os
import random<jupyter_output><empty_output><jupyter_text>Задача 9.  Использовать детектор углов Харриса и детектор особыхточек Ши-Томаси, исследовать влияние преобразований изображений (аффинные и перспективные преобразования, изменение яркости, контраста), а также параметров алгоритмов на результаты обнаружения локальных особенностей1.Harris corner detector(cv::cornerHarris);2.Shi-Tomachi(cv::goodFeaturesToTrack);3.Преобразованияизображений(cv::warpAffine,cv::warpPerspective)<jupyter_code>img = cv.imread('Task-9.jpg')
harris_img = img.copy()
shi_tomachi_img = img.copy()
rotated_img = img
#
bright_size = 10
contrast_size = 10
angle_size = 0.0
scale_size = 1.0
marker_list = list()
marker_list.append(cv.MARKER_CROSS)
marker_list.append(cv.MARKER_DIAMOND)
marker_list.append(cv.MARKER_SQUARE)
marker_list.append(cv.MARKER_STAR)
marker_list.append(cv.MARKER_TILTED_CROSS)
marker_list.append(cv.MARKER_TRIANGLE_DOWN)
marker_list.append(cv.MARKER_TRIANGLE_UP)
marker_type = 2
marker_size = 2
# For affine
height, width = img.shape[:2]
center = (width / 2, height / 2)
# For perpective
point_list=list()
point_list.append((0, 0))
point_list.append((img.shape[1], 0))
point_list.append((img.shape[1], img.shape[0]))
point_list.append((0, img.shape[0]))
point_for_change = 0
# For Harris 
block_size = 2
k_size = 3
k_p = 0.001
show_gray_har = 0
# For Shi_Tomachi
corners_count = 80
corners_quality = 0.05
minimal_distance = 5
show_gray_shi = 0

def update():
    global rotated_img
    rotated_img = img.copy()
    change_brightness(bright_size)
    change_contrast(contrast_size)
    rotate_matrix = cv.getRotationMatrix2D(center, angle_size, scale_size)
    rotated_img = cv.warpAffine(rotated_img, rotate_matrix, (width, height))
    matrix = cv.getPerspectiveTransform( np.float32([[0, 0], [img.shape[1], 0], [img.shape[1], img.shape[0]], [0, img.shape[0]]]), \
         np.float32(point_list))
    rotated_img = cv.warpPerspective(rotated_img, matrix, (img.shape[1], img.shape[0]), cv.INTER_CUBIC, borderMode = cv.BORDER_CONSTANT, borderValue = (0, 0, 0))
    cv.imshow('Pic', rotated_img)
    update_Harris()
    update_Shi_tomachi()


def change_brightness( brightness):
    global rotated_img
    if brightness != 0:
        rotated_img = cv.addWeighted(rotated_img, (255 - brightness) / 255, rotated_img, 0, brightness)



def change_contrast( contrast):
    global rotated_img
    if contrast != 0:
        f = 131 * (contrast + 127) / (127 * (131 - contrast))
        rotated_img = cv.addWeighted(rotated_img, f, rotated_img, 0, 127 * (1 - f))


def change_brightness_size(val):
    global bright_size
    bright_size = val
    update()


def change_contrast_size(val):
    global contrast_size
    contrast_size = val
    update()


def change_rotate_angle(val):
    global angle_size
    angle_size = val
    update()


def change_rotate_scale(val):
    global scale_size
    if val > 0:
        scale_size = val / 10.0
        update()


def change_point_for_changing(val):
    global point_for_change
    point_for_change = val


def change_point_x_val(val):
    global point_list
    _, old_y = point_list[point_for_change]
    point_list[point_for_change] = (val, old_y)
    update()   


def change_point_y_val(val):
    global point_list
    old_x, _ = point_list[point_for_change]
    point_list[point_for_change] = (old_x, val)
    update() 

    
def return_to_default(val):
    global point_list
    global scale_size
    global angle_size
    global contrast_size
    global bright_size
    scale_size = 1
    angle_size = 0
    point_list[0] = (0, 0)
    point_list[1] = (img.shape[1], 0)
    point_list[2] = (img.shape[1], img.shape[0])
    point_list[3] = (0, img.shape[0])
    update()

def update_Harris(gray = None):
    gray = cv.cvtColor(rotated_img, cv.COLOR_BGR2GRAY)
    corners = cv.cornerHarris(gray, block_size, k_size, k_p)
    harris_img = rotated_img.copy()
    if show_gray_har == 0:
        harris_img[corners > 0.01 * corners.max()] = [0, 255, 0]
        cv.imshow('Harris', harris_img)
    else:
        harris_img[corners > 0.01 * corners.max()] = [0, 0, 255]
        cv.imshow('Harris', harris_img)

def change_block_size(val):
    global block_size
    block_size = val
    update_Harris()


def change_k_size(val):
    global k_size
    if val % 2 == 0:
        val += 1
    k_size = val
    update_Harris()


def change_k_p(val):
    global k_p
    if val > 0:
        k_p = val / 100
        update_Harris()


def change_res_col_h(val):
    global show_gray_har
    show_gray_har = val
    update_Harris()
def draw_markers_shi(img_, corners, color =  (0, 255, 0)):
    corners_int = np.int0(corners)
    for corner in corners_int:
        x, y = corner.ravel()
        cv.drawMarker(img_, (x, y), color, marker_list[marker_type], marker_size)


def update_Shi_tomachi():
    gray = cv.cvtColor(rotated_img, cv.COLOR_BGR2GRAY)
    corners = cv.goodFeaturesToTrack(gray, corners_count, corners_quality, minimal_distance, mask = cv.inRange(gray, 1, 255))
    shi_tomachi_img = rotated_img.copy()
    if show_gray_shi == 0:
        draw_markers_shi(shi_tomachi_img, corners)
        cv.imshow('Shi tomachi', shi_tomachi_img)
    else:
        draw_markers_shi(shi_tomachi_img, corners, (0, 0, 255))
        cv.imshow('Shi tomachi', shi_tomachi_img)

def change_corners_count(val):
     global corners_count
     if val > 0:
         corners_count = val
         update_Shi_tomachi()


def change_corners_quality(val):
    global corners_quality
    if val > 0:
        corners_quality = val / 100.0
        update_Shi_tomachi()


def change_minimal_distance(val):
    global minimal_distance
    minimal_distance = val
    update_Shi_tomachi()

def change_res_col_shi(val):
    global show_gray_shi
    show_gray_shi = val
    update_Shi_tomachi()


def change_marker_type(val):
    global marker_type
    marker_type = val
    update_Shi_tomachi()


def change_marker_size(val):
    global marker_size
    marker_size = val
    update_Shi_tomachi()
# Do some things with begin pic
cv.imshow('Pic', img)
cv.namedWindow('Control')
cv.createTrackbar('Brightness', 'Control', 0, 255, change_brightness_size)
cv.createTrackbar('Contrast', 'Control', 0, 128, change_contrast_size)
cv.createTrackbar('Angle', 'Control', 0, 360, change_rotate_angle)
cv.createTrackbar('Scale', 'Control', 10, 360, change_rotate_scale)
cv.createTrackbar('Point', 'Control', 0, 3, change_point_for_changing)
cv.createTrackbar('X', 'Control', 0, img.shape[1] - 1, change_point_x_val)
cv.createTrackbar('Y', 'Control', 0, img.shape[0] - 1, change_point_y_val)
cv.namedWindow('Control2')
cv.createTrackbar('Return', 'Control2', 0, 1, return_to_default)
#Harris corners
cv.imshow('Harris', harris_img)
cv.createTrackbar('block size', 'Harris', 2, 50, change_block_size)
cv.createTrackbar('kernel size', 'Harris', 3, 31, change_k_size)
cv.createTrackbar('k', 'Harris', 10, 100, change_k_p)
cv.createTrackbar('is gray', 'Harris', 0, 1, change_res_col_h)
#Shi tomachi corners
cv.imshow('Shi tomachi', shi_tomachi_img)
cv.createTrackbar('corners count', 'Shi tomachi', 80, 300, change_corners_count)
cv.createTrackbar('quality', 'Shi tomachi', 5, 100, change_corners_quality)
cv.createTrackbar('min distance', 'Shi tomachi', 5, 100, change_minimal_distance)
cv.createTrackbar('is gray', 'Shi tomachi', 0, 1, change_res_col_shi)
cv.createTrackbar('Marker type', 'Shi tomachi', 0, len(marker_list) - 1, change_marker_type)
cv.createTrackbar('Marker size', 'Shi tomachi', 2, 30, change_marker_size)

cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task 10<jupyter_code>from __future__ import print_function
import numpy as np
import cv2 as cv<jupyter_output><empty_output><jupyter_text>Задача 10.  Реализовать поиск соответствия особых точек на двух изображений (feature matching), исследовать работу в реальных условиях.<jupyter_code>MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15

def alignImages(im1, im2):

  # Convert images to grayscale
  im1Gray = cv.cvtColor(im1, cv.COLOR_BGR2GRAY)
  im2Gray = cv.cvtColor(im2, cv.COLOR_BGR2GRAY)

  # Detect ORB features and compute descriptors.
  orb = cv.ORB_create(MAX_FEATURES)
  keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
  keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)

  # Match features.
  matcher = cv.DescriptorMatcher_create(cv.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
  matches = matcher.match(descriptors1, descriptors2, None)

  # Sort matches by score
  matches.sort(key=lambda x: x.distance, reverse=False)

  # Remove not so good matches
  numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
  matches = matches[:numGoodMatches]

  # Draw top matches
  imMatches = cv.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
  cv.imshow("Matches", imMatches)

  # Extract location of good matches
  points1 = np.zeros((len(matches), 2), dtype=np.float32)
  points2 = np.zeros((len(matches), 2), dtype=np.float32)

  for i, match in enumerate(matches):
    points1[i, :] = keypoints1[match.queryIdx].pt
    points2[i, :] = keypoints2[match.trainIdx].pt

  # Find homography
  h, mask = cv.findHomography(points1, points2, cv.RANSAC)

  # Use homography
  height, width, channels = im2.shape
  im1Reg = cv.warpPerspective(im1, h, (width, height))

  return im1Reg, h
#Test 1
# Read reference image
imReference = cv.imread("form.jpg", cv.IMREAD_COLOR)

# Read image to be aligned
im = cv.imread("scanned-form.jpg", cv.IMREAD_COLOR)
# Registered image will be resotred in imReg.
# The estimated homography will be stored in h.
imReg, h = alignImages(im, imReference)
cv.imshow("Full image", imReference)
cv.imshow("Scanned image", im)
cv.waitKey(0)
cv.destroyAllWindows()
# Print estimated homography
print("Estimated homography : \n",  h)
#Test 2
# Read reference image
imReference = cv.imread("Colosseo4.jpg", cv.IMREAD_COLOR)

# Read image to be aligned
im = cv.imread("Colosseo2.jpg", cv.IMREAD_COLOR)
imReference =cv.resize(imReference, (im.shape[1], im.shape[0]))
# Registered image will be resotred in imReg.
# The estimated homography will be stored in h.
imReg, h = alignImages(im, imReference)
cv.imshow("Full image", imReference)
cv.imshow("Scanned image", im)
cv.waitKey(0)
cv.destroyAllWindows()
# Print estimated homography
print("Estimated homography : \n",  h)
#Test 3
# Read reference image
imReference = cv.imread("Lays1.png", cv.IMREAD_COLOR)

# Read image to be aligned
im = cv.imread("Lays2.jpg", cv.IMREAD_COLOR)
# Registered image will be resotred in imReg.
# The estimated homography will be stored in h.
imReg, h = alignImages(im, imReference)
cv.imshow("Full image", imReference)
cv.imshow("Scanned image", im)
cv.waitKey(0)
cv.destroyAllWindows()
# Print estimated homography
print("Estimated homography : \n",  h)<jupyter_output>Estimated homography : 
 [[ 6.50327264e-01  9.02902079e-02 -3.57634986e+01]
 [-5.43999893e-02  6.98701225e-01 -7.97120521e+01]
 [ 7.24375156e-05  1.92390043e-04  1.00000000e+00]]<jupyter_text>Task 11<jupyter_code>import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
from scipy.ndimage import label


img = cv.imread("segmentation.jpg")
img = cv.resize(img, (800, 800))
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, img_morph = cv.threshold(gray, 0, 255, cv.THRESH_OTSU)
img_morph = cv.morphologyEx(img_morph, cv.MORPH_OPEN, np.ones((3, 3), dtype=int))
img_copy = img.copy()
low_threshold = 0
high_threshold = 0
iteration_num = 5
ret, thresh = cv.threshold(gray, 20, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)

def update():
    global ret
    global thresh
    # delitating image
    dilated_img = cv.dilate(img_morph, None, iterations = iteration_num)
    dilated_img = dilated_img - cv.erode(dilated_img, None)
    distances_transform = cv.distanceTransform(img_morph, cv.DIST_L2, 3)
    # show distances_transform
    cv.imshow('distances', distances_transform)
    distances_transform = ((distances_transform - distances_transform.min()) / (distances_transform.max() - distances_transform.min()) * 255).astype(np.uint8)
    ret, distances_transform = cv.threshold(distances_transform, low_threshold, high_threshold, cv.THRESH_BINARY)
    # show thresh changing
    cv.imshow("thresh", distances_transform)
    label_, num_features = label(distances_transform)
    # Multiplying label array on 255 / (number of featuter + 1) to prevent deviding on zero
    label_ = label_ * (255 / (num_features + 1))
    # Completing the markers now.
    label_[dilated_img == 255] = 255
    # Using watershed
    label_ = label_.astype(np.int32)
    labels = cv.watershed(img, label_)
    cv.imshow('labels', cv.convertScaleAbs(labels))
    # Changing values that is equal -1
    label_[label_ == -1] = 0
    # Getting outlines as result
    markers = 255 - label_.astype(np.uint8)
    markers[markers != 255] = 0
    markers = cv.dilate(markers, None)
    #copy original image to add on it edges
    result = img.copy()
    result[markers == 255] = (0, 255, 0)
    cv.imshow('Outlines', markers)
    cv.imshow('Result', result)

def change_low_treshold(val):
    global low_threshold
    low_threshold = val
    update()

def change_high_treshold(val):
    global high_threshold
    high_threshold = val
    update()

def change_iteration_num(val):
    global iteration_num
    iteration_num = val
    update()
cv.imshow("thresh", thresh)
cv.createTrackbar('thresh low', 'thresh', 20, 500, change_low_treshold)
cv.createTrackbar('thresh high', 'thresh', 255, 500, change_high_treshold)
cv.createTrackbar('iterations', 'thresh', 5, 100, change_iteration_num)
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output><empty_output><jupyter_text>Task 12.4<jupyter_code>import cv2 as cv
from mtcnn import MTCNN
from deepface import DeepFace
from deepface.basemodels import VGGFace, OpenFace, Facenet, FbDeepFace
import matplotlib.pyplot as plt
import os
detector = MTCNN() # создание детектора
def detect_faces(img):
    result = detector.detect_faces(img)  # обнаружение лиц на изображении
    faces_list = list()
    boundings = list()
    for i in range(len(result)): 
        bounding_box = result[i]['box']  #  ограничивающие рамки
        faces_list.append(img[bounding_box[1]: bounding_box[1] + bounding_box[3], bounding_box[0]:bounding_box[0] + bounding_box[2]])
        boundings.append(result[i]['box'])
        #cv.rectangle(image, (bounding_box[0], bounding_box[1]),
        #(bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),(0,155,255), 2) #  ограничение области на изображении      
    return faces_list, boundings
def get_img_stats(img_path):
    pred = DeepFace.analyze(img_path = img_path,  enforce_detection = False, actions = ['emotion', 'age', 'gender', 'race'])
    return pred
    #for key in pred['emotion']:
    #    if pred['emotion'][key] > 10:
    #        print(key, int(pred['emotion'][key]), "%") 
    #print("Age:", pred['age'])
    #print("Sex:", pred['gender'])
    #for key in pred['race']:
    #    if pred['race'][key] > 10:
    #        print(key, int(pred['race'][key]), "%")

def save_faces(faces):
    save_file_names = list()
    for i in range(len(faces)):
        save_file_names.append("face"+str(i)+".jpg")
        cv.imwrite(save_file_names[i], faces[i])
    return save_file_names

def delete_faces(face_pathes):
    for i in range(len(face_pathes)):
        os.remove(face_pathes[i])

def show_age_and_gender(img_path):
    img = cv.imread(img_path)
    img2 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    faces, bound = detect_faces(img2)
    save_pathes = save_faces(faces)
    face_pred = list()
    text_add_move = 30
    for i in range(len(save_pathes)):
        text_move = text_add_move
        face_pred.append(get_img_stats(save_pathes[i]))
        bounding_box = bound[i]
        cv.rectangle(img, (bounding_box[0], bounding_box[1]),
        (bounding_box[0] + bounding_box[2], bounding_box[1] + bounding_box[3]),(0,255,0), 2) #  ограничение области на изображении      
        font = cv.FONT_HERSHEY_SIMPLEX
        for key in face_pred[i]['emotion']:
            if face_pred[i]['emotion'][key] > 10:
                cv.putText(img, (key +" "+ str(int(face_pred[i]['emotion'][key]))+"%"), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 0, 0), 2, cv.LINE_AA)
                cv.putText(img, (key +" "+ str(int(face_pred[i]['emotion'][key]))+"%"), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 255, 0), 1, cv.LINE_AA)
                text_move += text_add_move
        cv.putText(img, ("Age:" + str(face_pred[i]['age'])), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 0, 0), 2, cv.LINE_AA)
        cv.putText(img, ("Age:" + str(face_pred[i]['age'])), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 255, 0), 1, cv.LINE_AA)
        text_move+=text_add_move
        cv.putText(img, ("Sex:" + str(face_pred[i]['gender'])), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 0, 0), 2, cv.LINE_AA)
        cv.putText(img, ("Sex:" + str(face_pred[i]['gender'])), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 255, 0), 1, cv.LINE_AA)
        text_move += text_add_move
        for key in face_pred[i]['race']:
            if face_pred[i]['race'][key] > 10:
                cv.putText( img,  (str(key) + " " + str(int(face_pred[i]['race'][key]))+"%"), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 0, 0), 2, cv.LINE_AA)
                cv.putText( img,  (str(key) + " " + str(int(face_pred[i]['race'][key]))+"%"), 
                (bounding_box[0] + 10, bounding_box[1] + text_move), 
                font, 1, (0, 255, 0), 1, cv.LINE_AA)
                text_move += text_add_move
    delete_faces(save_pathes)
    cv.imshow("Pic", img)
pictures = ['task12.jpeg', 'task12.jpg', 'task12-1.jpg', 'task12-2.jpg', 'task12-3.jpg', 'task12-4.jpg']
for i in pictures:   
    show_age_and_gender(i)
    cv.waitKey(0)
    cv.destroyAllWindows()
show_age_and_gender()
cv.waitKey(0)
cv.destroyAllWindows()
show_age_and_gender('task12-test.jpg')
cv.waitKey(0)
cv.destroyAllWindows()
show_age_and_gender('task12-2.jpg')
cv.waitKey(0)
cv.destroyAllWindows()
show_age_and_gender('task12-7.jpeg')
cv.waitKey(0)
cv.destroyAllWindows()<jupyter_output>Action: race: 100%|██████████| 4/4 [00:00<00:00,  9.86it/s]
Action: race: 100%|██████████| 4/4 [00:00<00:00, 10.23it/s]
Action: race: 100%|██████████| 4/4 [00:00<00:00,  9.78it/s]
Action: race: 100%|██████████| 4/4 [00:00<00:00, 10.23it/s]
Action: race: 100%|██████████| 4/4 [00:00<00:00,  9.99it/s]
Action: race: 100%|██████████| 4/4 [00:00<00:00, 10.18it/s]
{'fraction_non_alphanumeric': 0.1318978750908944, 'fraction_numerical': 0.0394279712369718, 'mean_word_length': 3.6209632256860185, 'pattern_counts': {'":': 13, '<': 105, '<?xml version=': 0, '>': 103, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '21', 'dir': 'jupyter-structured-clean-dedup', 'id': '305088', 'license': 'MIT', 'n_tokens_mistral': 19982, 'n_tokens_neox': 18539, 'n_words': 4224, 'path': 'SAIP.ipynb', 'repo_name': 'SkivHisink/OpenCV_Practice', 'size': '49508'}