先上代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import cv2
import os
import numpy as np
import uuid
#coco
#获取图片固定位置的颜色坐标,并且通过坐标点颜色填充整张图片
'''------------------------------------------------第三--------------------------------------------------------'''
# 获取图片坐标bgr值
def get_pix_bgr(image_path: str, x: int, y: int):
ext = os.path.basename(image_path).strip().split('.')[-1]
if ext not in ['png', 'jpg']:
raise Exception('format error')
img = cv2.imread(image_path)
px = img[y, x]
blue = img[y, x, 0]
green = img[y, x, 1]
red = img[y, x, 2]
return blue, green, red
'''-----------------------------------------------第二----------------------------------------------------------'''
# 构建纯色图
def make_one_color_pic(output_dir: str, image_path: str, coordinates: tuple, resolution: tuple):
blue, green, red = get_pix_bgr(image_path, coordinates[0], coordinates[1])
img = np.zeros((resolution[1], resolution[0], 3), np.uint8)
# 创建BGR纯色图
img[:] = [blue, green, red]
result_image = os.path.join(output_dir, '{}.jpg'.format(uuid.uuid1().hex))
cv2.imwrite(result_image, img)
return result_image
'''------------------------------------------------第一-------------------------------------------------------'''
#获取固定点坐标
def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
xy = "%d,%d" % (x, y)
print(x,y)
cv2.circle(img, (x, y), 2, (0, 0, 255))
cv2.putText(img, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,1.0, (0,0,255))
cv2.imshow("image", img)
#获得图片大小
wh = img.shape[0:2]
print(make_one_color_pic('E:/project/Template_detection/Image_preprocessing/', 'E:/project/Template_detection/Image_preprocessing/aniya_bear.jpg', (x, y), (wh[0], wh[1])))
'''---------------------------------------------开始-------------------------------------------------------------'''
if __name__ == '__main__':
img = cv2.imread('E:/project/Template_detection/Image_preprocessing/aniya_bear.jpg')
cv2.namedWindow("image")
# cv2.setMouseCallback(winname, onMouse, userdata=0)
# winname: 自定义的窗口名
# onMouse:鼠标事件的回调函数(在发生鼠标事件时执行)
# userdata:传递给回调函数的可选参数
cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN)
while (1):
cv2.imshow("image", img)
key = cv2.waitKey(5) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
#print(make_one_color_pic('E:/project/Template_detection/Image_preprocessing/', 'E:/project/Template_detection/Image_preprocessing/anniya.jpg', (60, 240), (1080, 1920)))
实验图片:
结果展示:
我选的原图有点大了,可以自己设定图片的大小。
ps:加油加油