编程语言
首页 > 编程语言> > python opencv图片拼接源码

python opencv图片拼接源码

作者:互联网

import cv2
import numpy as np
import time

def image_handle(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    grayshape=gray.shape
    print('图片大小',grayshape)
    high=grayshape[0]
    width=grayshape[1]
    cuty1=500
    cuty2=0
    gray_cut = gray[cuty1:int(high)-cuty2, int(width/2)-100:int(width/2)+100]
    gray_sample = gray[int(high)-20:int(high), int(width/2)-100:int(width/2)+100]
    print('采样区平均像素值:',np.mean(gray_sample))
    sample_value = np.mean(gray_sample)
    ret, binary = cv2.threshold(gray_cut, sample_value - 15, 255, cv2.THRESH_BINARY)
    print("threshold value %s" % ret)
    img_300x300 = cv2.copyMakeBorder(binary, 30, 30, 30, 30,
                                     cv2.BORDER_CONSTANT,
                                     value=255)
    contours, heriachy = cv2.findContours(img_300x300, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    for i in range(len(contours)):
        cv2.drawContours(img_300x300, contours, i, 128, 2)
    mylist = []
    for i in range(len(contours)):
        if len(contours[i]) > 5:
            mylist.append(i)
    dx = []
    dy = []
    for j in range(len(mylist)):
        a = contours[mylist[j]]
        for i in range(len(a)):
            b = a[i]
            c = b[0]
            if (c[0] > 226):
                dx.append(c[0])
                dy.append(c[1])
    ndy = len(dy)
    di = 0
    for i in range(ndy):
        if dy[i - di] < (max(dy) - 3):
            del dy[i - di]
            del dx[i - di]
            di = di + 1
    dxa = np.mean(dx)+int(width/2)-100-30
    dya = np.mean(dy)+cuty1-30
    return dxa,dya

def image_stitching(image_after,image2_before):
    m1 = image_handle(image_after)
    # cv2.circle(image_after, (int(m1[0]), int(m1[1])), 10, (0, 0, 255), -1)
    m2 = image_handle(image2_before)
    # cv2.circle(image2_before, (int(m2[0]), int(m2[1])), 10, (0, 0, 255), -1)
    d = int(m1[1] - m2[1])
    print(d)
    image2_shape = image2_before.shape
    print('图片大小', image2_shape)
    high = image2_shape[0]
    width = image2_shape[1]
    image2_before1 = image2_before[0:high - d, 0:width]
    image2_before2 = cv2.copyMakeBorder(image2_before1, d, 0, 0, 0,
                                     cv2.BORDER_CONSTANT,
                                     value=0)
    img_stitching = np.where(image_after < image2_before2, image2_before2, image_after)
    return img_stitching

if __name__ == "__main__":
    start = time.time()
    print(start)
    src = cv2.imread('po3_I135.jpg')
    src1 = cv2.imread('po1_I135.jpg')
    src3=image_stitching(src,src1)
    cv2.namedWindow('dddddd', 0)
    cv2.imshow('dddddd', src3)

    print(time.time()-start)

    cv2.waitKey(0)

 

标签:gray,width,python,image,cv2,opencv,int,源码,image2
来源: https://www.cnblogs.com/caiya/p/15103948.html