opencv-python常用函数复制粘贴

本文汇总了OpenCV-Python库中常用的函数,方便开发者快速查找和使用,包括图像读取、处理、显示等功能。

#二值化
retval, dst = cv2.threshold(im_gray, 50, 255, cv2.THRESH_BINARY) 
dst = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 3) 

#轮廓 别人总结的一个帖子 https://segmentfault.com/a/1190000015663722
img, contours, hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)    
cv2.drawContours(img_color,contours,-1,(0,0,255),3) ##thickness=cv2.FILLED填充轮廓
rect = cv2.boundingRect(contour) 

#bounder
dst = cv2.copyMakeBorder(src, 50,50,50,50, cv2.BORDER_CONSTANT,value = [255,255,255]) 

#通道转换
img_color = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

# 旋转90度:  -1:顺时针1次,2:逆时针2次
dst = np.rot90(src,-1)

#旋转
img_ex = cv2.copyMakeBorder(img, 300,300,300,300, cv2.BORDER_REPLICATE)
(h, w) = img_ex.shape[:2]
center = (w / 2, h / 2)
M_rotate = cv2.getRotationMatrix2D(center, d, 1)
img_ex_rotated = cv2.warpAffine(img_ex, M_rotate, (w, h))
img_rotated = img_ex_rotated[299:299+imgh,299:299+imgw]

#opencv写画
cv2.putText(frame, time_stamp, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)
cv2.rectangle(frame, (x1, y1), (x2, y2), (255,255,255) ,2)

#写txt
traintxt = "train.txt"
ftrain = open(traintxt, "w")
ftrain.write(''+'\n')
ftrain.close()

#读txt
imagelist = open('train.txt', 'r').readlines()

#esc退出
if cv2.waitKey(0)==27:
    cv2.destroyAllWindows()

# voc-color map, N个不同颜色的color
def voc_colormap(N=256):
    def bitget(val, idx): 
        return ((val & (1 << idx)) != 0)
    cmap = np.zeros((N, 3), dtype=np.uint8)
    for i in range(N):
        r = g = b = 0
        c = i
        for j in range(8):
            r |= (bitget(c, 0) << 7 - j)
            g |= (bitget(c, 1) << 7 - j)
            b |= (bitget(c, 2) << 7 - j)
            c >>= 3
        #print([r, g, b])
        cmap[i, :] = [r, g, b]
    return cmap

# 读取视频
cap = cv2.VideoCapture(0)  #读取摄像头
#cap = cv2.VideoCapture("test.mp4")  #读取视频文件
while(True):
    ret, frame = cap.read()
    if ret:
        cur_time = cap.get(cv2.CAP_PROP_POS_MSEC)
        cur_id = cap.get(cv2.CAP_PROP_POS_FRAMES)
        cur_fps = cap.get(cv2.CAP_PROP_FPS)
        cv2.imshow("frame", frame)
        if cv2.waitKey(30) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()

# 写视频
cap = cv2.VideoCapture(0)
#cap = cv2.VideoCapture("test.mp4")
fps = 30
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc('M','P','E','G'), fps, size)
 
while(True):
    ret, frame = cap.read()
    if ret:
        videoWriter.write(frame)
        cv2.imshow("frame", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
videoWriter.release()


# 解析 xml
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml') 
rootnode = tree.getroot() 
node = rootnode.find('name') #找tag为‘name’的子节点
nodes = rootnode.findall('name') #找所有的tag为‘name’的子节点
print(node.tag, node.attrib, node.text) #节点的名称,节点属性,节点内容


#保持原图比例将长边缩放到target_size
def resize_by_largeborder(img, target_size)
    largeborder = max(img.shape)    
    imgh,imgw = img.shape[:2]
    scalefactor = target_size/largeborder   
    newh = int(imgh*scalefactor)
    neww = int(imgw*scalefactor)      
    img = cv2.resize(img,(neww,newh),interpolation=cv2.INTER_AREA)
    return img

def resize_and_padding(image, new_shape):
    '''
        image : (h, w) or (h, w, c)
        new_shape : (h, w)
    '''
    new_shape = tuple(new_shape)
    imgh, imgw = image.shape[:2]
    h, w = new_shape
    scalefactor = np.min((w/imgw, h/imgh))
    neww = int(imgw*scalefactor)
    newh = int(imgh*scalefactor)
    if image.ndim == 2:
        new_image = np.zeros(new_shape, image.dtype)
    else:
        new_image = np.zeros(new_shape+(image.shape[2],), image.dtype)
    offseth, offsetw = (h-newh)//2, (w-neww)//2
    image = cv2.resize(image,(neww,newh),interpolation=cv2.INTER_NEAREST)
    new_image[offseth:offseth+newh, offsetw:offsetw+neww] = image
    return new_image


#在大图中有重复的截取出所有小图像块
cs = 512  # crop size
min_ol = 0.4  # min overlap
max_os = 1 - min_ol  # max offset
def crop2patch(h, w):
    if h <= cs or w <= cs:
        # TODO padding to square
        return [], False

    n_w = math.ceil((w - cs) / (cs * max_os))
    n_h = math.ceil((h - cs) / (cs * max_os))
    delta_h = (h - cs) / n_h
    delta_w = (w - cs) / n_w
    loc = []
    for i in range(n_h + 1):
        for j in range(n_w + 1):
            t = int(i * delta_h)
            b = int(i * delta_h + cs)
            l = int(j * delta_w)
            r = int(j * delta_w + cs)
            loc.append((t, b, l, r))
    return loc, True


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值