图像处理python代码小应用

直方图匹配:https://www.cnblogs.com/picassooo/p/11504937.html
仿射变换:https://blog.csdn.net/liuweiyuxiang/article/details/82799999
https://www.mdeditor.tw/pl/p38J

1.直方图匹配

直方图匹配代码:

import cv2
import numpy as np

img = cv2.imread('../imgs/001.JPG')
ref = cv2.imread('../imgs/002.JPG')

out = np.zeros_like(img)
_, _, colorChannel = img.shape
for i in range(colorChannel):
    print(i)
    hist_img, _ = np.histogram(img[:, :, i], 256)  # get the histogram
    hist_ref, _ = np.histogram(ref[:, :, i], 256)
    cdf_img = np.cumsum(hist_img)  # get the accumulative histogram
    cdf_ref = np.cumsum(hist_ref)

    for j in range(256):
        tmp = abs(cdf_img[j] - cdf_ref)
        tmp = tmp.tolist()
        idx = tmp.index(min(tmp))  # find the smallest number in tmp, get the index of this number
        out[:, :, i][img[:, :, i] == j] = idx

cv2.imwrite('003.jpg', out)
print('Done')

原图:
| 001.JPG
|002.JPG
|

直方图匹配结果:
在这里插入图片描述

2.仿射变换

代码:

import cv2
import numpy as np


def mouse_handler(event, x, y, flags, data):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(data['im'], (x, y), 3, (0, 0, 255), 5, 16)
        cv2.namedWindow("Image", 0)
        cv2.imshow("Image", data['im'])
        if len(data['points']) < 4:
            data['points'].append([x, y])


def get_four_points(im):
    data = {'im': im.copy(), 'points': []}
    # Set the callback function for any mouse event
    cv2.namedWindow("Image", 0)
    cv2.imshow('Image', im)
    # 请注意你标记点的数据,是顺时针,需要与pst_src 方向一致
    cv2.setMouseCallback("Image", mouse_handler, data)
    cv2.waitKey(0)
    # Convert array to np.array
    # 竖直方向堆叠起来;;;
    points = np.vstack(data['points']).astype(float)
    return points


if __name__ == '__main__':
    img_src = cv2.imread("../imgs/001.JPG")
    size = img_src.shape
    # 取得四个坐标
    pst_src = np.array(
        [
            [0, 0], [size[1] - 1, 0],
            [size[1] - 1, size[0] - 1],
            [0, size[0] - 1]
        ], dtype=float
    )
    # Read the destination image
    img_dst = cv2.imread("../imgs/supermarket.JPG")

    print("Click on four corners of bllboard and the press ENTER")
    four_point = get_four_points(img_dst)

    # Calculate  Homography between  source and destination points
    h, status = cv2.findHomography(pst_src, four_point)

    im_temp = cv2.warpPerspective(img_src, h, (img_dst.shape[1], img_dst.shape[0]))

    cv2.fillConvexPoly(img_dst, four_point.astype(int), 0, 16)

    # add wraped source image to destination image

    img_dst = img_dst + im_temp
    cv2.namedWindow("Image", 0)
    cv2.imshow("Image", img_dst)
    cv2.waitKey(0)

原图:
在这里插入图片描述
结果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值