python--opencv的基本使用
python–opencv的基本使用
安装 pip install opencv-python 引用 import cv2
常用函数
读图片:
原型
Python:retval=cv.imread(filename[, flags])
image = cv2.imread(full_path_i)
存照片:
Pyhton:retval=cv.imwrite(filename, img[, params])
cv2.imwrite(img_path+/out/+file_name+line_+str(line_c)+.png, image)
图片宽高:
h w:image.shape[0],image.shape[1]
图片的crop
示例代码:
x1 = int(image.shape[1]/5) x2 = int(image.shape[1]*4/5) y1 = int(image.shape[0]*3/4) y2 = int(image.shape[0]) hight = int((y2 - y1)/2) width = x2 - x1 crop_img= image[y1:y1+hight, x1:x1+width]
颜色转换
python: dst=cv.cvtColor(src, code[, dst[, dstCn]]) 参数: 示例代码: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
raw域颜色转换
cv::COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, //RGGB cv::COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, //GRGB cv::COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, //BGGR cv::COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, //GBGR
画线
cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 1)
canny边缘线
edges = cv2.Canny(gray, 5, 15, apertureSize=3) # apertureSize参数默认其实就是3
HoughLinesP直线检测
lines = cv2.HoughLinesP(edges, 3, np.pi / 180, 60, minLineLength=200, maxLineGap=10) if lines is not None: for line in lines: x1, y1, x2, y2 = line[0]
Proj
png 贴图
org_img = cv2.imread(org.png) #背景 img_apple = cv2.imread(apple.png) #前景小图 rows, cols = img_apple.shape[:2] h, w = org_img.shape[:2] roi_org = org_img[:h, :w] roi_targ = org_img[500:500+rows, 500:500+cols] #指定区域做融合 # 创建掩膜 img2gray = cv2.imread(apple.png,0) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # 保留除logo外的背景 img1_bg = cv2.bitwise_and(roi_targ, roi_targ, mask=mask_inv) #腐蚀处理 img_out = cv2.add(img1_bg, img_apple) # 进行融合 #img_out = cv2.add(img,0, img_apple,1, 1) org_img[500:500+rows, 500:500+cols] = img_out cv2.imwrite(out.png,org_img)