- 本文是个人使用Python处理图片的电子笔记,由于水平有限,难免出现错漏,敬请批评改正。
- 更多精彩内容,可点击进入我的个人主页查看
- 熟悉Python
- Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。
- Python 3.x (面向对象的高级语言)
import cv2
import numpy as np
def is_RecA_RecB_interSect(RecA, RecB): # Rec = [xmin,ymin,xmax,ymax]
# 获取交集区域的[xmin,ymin,xmax,ymax]
x_A_and_B_min = max(RecA[0], RecB[0])
y_A_and_B_min = max(RecA[1], RecB[1])
x_A_and_B_max = min(RecA[2], RecB[2])
y_A_and_B_max = min(RecA[3], RecB[3])
# 计算交集部分面积, 当(xmax - xmin)为负时,说明A与B框无交集,直接置为0。 (ymax - ymin)同理。
interArea = max(0, x_A_and_B_max - x_A_and_B_min) * max(0, y_A_and_B_max - y_A_and_B_min)
return interArea > 0
def merge_RecA_RecB(RecA, RecB): # Rec = [xmin,ymin,xmax,ymax]
# 获取合并区域的[xmin,ymin,xmax,ymax]
xmin = min(RecA[0], RecB[0])
ymin = min(RecA[1], RecB[1])
xmax = max(RecA[2], RecB[2])
ymax = max(RecA[3], RecB[3])
return (xmin,ymin), (xmax,ymax)
if __name__ =="__main__":
# img = cv2.imread("5_cemian1_1_Image-0002.jpg")
# img_res = img.copy()
# RecA = [256,47,259,126]
# RecB = [254,113,260,426]
img = cv2.imread("cat1.jpg")
img_res = img.copy()
RecA = [80,90,330,336]
RecB = [200,255,425,490]
# 绘制RecA和RecA
cv2.rectangle(img, (RecA[0],RecA[1]), (RecA[2],RecA[3]), (0, 0, 255), 2)
cv2.rectangle(img, (RecB[0],RecB[1]), (RecB[2],RecB[3]), (255, 0, 0), 2)
cv2.putText(img,'RecA_left_top:({},{})'.format(RecA[0],RecA[1]),(RecA[0]-20,RecA[1]-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,0),2)
cv2.putText(img,'RecA_right_bottom:({},{})'.format(RecA[2],RecA[3]),(RecA[2]-150,RecA[3]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,0),2)
cv2.putText(img,'RecB_left_top:({},{})'.format(RecB[0],RecB[1]),(RecB[0]-20,RecB[1]-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,0),2)
cv2.putText(img,'RecB_right_bottom:({},{})'.format(RecB[2],RecB[3]),(RecB[2]-200,RecB[3]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,0),2)
if is_RecA_RecB_interSect(RecA, RecB):
(xmin,ymin), (xmax,ymax) = merge_RecA_RecB(RecA, RecB)
# 绘制合并的框
cv2.rectangle(img_res, (xmin,ymin), (xmax,ymax), (0,165,255), 2)
cv2.putText(img_res,'left_top:({},{})'.format(xmin,ymin),(xmin-20,ymin-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,0),2)
cv2.putText(img_res,'right_bottom:({},{})'.format(xmax,ymax),(xmax-150,ymax+15), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,0),2)
cv2.imshow("img",img)
cv2.imshow("img_res",img_res)
cv2.waitKey()
cv2.destroyAllWindows()
更多精彩内容,可点击进入Python日常小操作专栏或我的个人主页查看