OpenCV em Python. Parte 2

Olá, Habr! Continuamos o tutorial sobre a biblioteca opencv em python. Para quem não leu a primeira parte, aqui: Parte 1 e todos os outros - leitura divertida!



part_2_logo



Introdução



Agora que você está familiarizado com o básico desta biblioteca, é hora de iniciar as transformações básicas das imagens: redimensionamento, deslocamento ao longo dos eixos, corte (corte), rotação.



Redimensionamento de imagem



, — . opencv resize():



def resizing():
    res_img = cv2.resize(img, (500, 900), cv2.INTER_NEAREST)


, , — , , — (). — , . , , . , (cv2.INTER_NEAREST) , — . opencv : cv2.INTER_AREA, cv2.INTER_LINEAR( ), cv2.INTER_CUBIC cv2.INTER_LANCZOS4. cv2.INTER_AREA, — cv2.INTER_LINEAR. , , / , 1.5 , — . . :



res_img_nearest = cv2.resize(img, (int(w / 1.4), int(h / 1.4)), 
                                 cv2.INTER_NEAREST)
res_img_linear = cv2.resize(img, (int(w / 1.4), int(h / 1.4)), 
                                cv2.INTER_LINEAR)


— , — :



conc_girl



. — . , :



res_girl



:



def resizing(new_width=None, new_height=None, interp=cv2.INTER_LINEAR):
    h, w = img.shape[:2]

    if new_width is None and new_height is None:
        return img

    if new_width is None:
        ratio = new_height / h
        dimension = (int(w * ratio), new_height)

    else:
        ratio = new_width / w
        dimension = (new_width, int(h * ratio))

    res_img = cv2.resize(img, dimension, interpolation=interp)


ratio. , None, / /. , dimension cv2.resize().





cv2.warpAffine() , , :



def shifting():
    h, w = img.shape[:2]
    translation_matrix = np.float32([[1, 0, 200], [0, 1, 300]])
    dst = cv2.warpAffine(img, translation_matrix, (w, h))
    cv2.imshow(',    ', dst)
    cv2.waitKey(0)


, translation_matrix :



1



— [1, 0, tx ], tx — , . tx , — .

— [ 0, 1, ty], ty — , . ty , — . , .

, , , cv2.warpAffine(), , — , — . , :



girl_right_and_down





, , :



def cropping():
    crop_img = img[10:450, 300:750]


numpy , (300, 10) (750, 450), 10 — y, 300 — x, 450 — y 750 — x. , , :



crop_face





, , — :



def rotation():
    (h, w) = img.shape[:2]
    center = (int(w / 2), int(h / 2))
    rotation_matrix = cv2.getRotationMatrix2D(center, -45, 0.6)
    rotated = cv2.warpAffine(img, rotation_matrix, (w, h))


, , , cv2.getRotationMatrix2D(). , opencv , . , , — . 0.6, 40%, , . numpy, cv2.warpAffine(). , :



rotated_girl



Agora que a segunda parte chegou ao fim, o código-fonte está disponível no github . Obrigado pela sua atenção! Te vejo em breve!




All Articles