图像处理快速入门
声明:菜鸡简单整理中
抠图(Matting)
一、算法研究:Alpha Matting Evaluation
二、处理工具:
1.Removebg-图片背景消除网站:removebg
2.win10画图3D的神奇选择(GrabCut算法)
3.简易的阈值处理:
灰度图
import cv2
def im2bw(img):
blur = cv2.GaussianBlur(img, (5, 5), 0) #高斯滤波
# 全局OTSU阈值
(thresh, th1) = cv2.threshold(blur, 0, 255, cv2.THRESH_OTSU)
# 自适应阈值
th2 = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
cv2.THRESH_BINARY_INV,11,2)
th3 = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
cv2.THRESH_BINARY_INV, 11, 2)
return th1, th2, th3
彩色图
import cv2
import numpy as np
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)#rgb转hsv空间
low = np.array([100, 43, 46]) #hsv中蓝色下限
up = np.array([124, 255, 255]) #hsv中蓝色上限
mask = cv2.inRange(hsv, low, up) # 低于low,高于up的值置0,low-up之间的值置为255
图片裁剪
import cv2
import numpy as np
import os
import tkinter as tk
from tkinter import filedialog
#img = cv2.imread('C:/Users/dell/r.jpg')#读原图
#img = cv2.imread('C:/Users/dell/r.jpg',0)#读灰度图
# GRAY=0.3*R+0.59*G+0.11*B #计算公式
# 弹出对话框选图
root = tk.Tk()
root.withdraw()
#Folderpath = filedialog.askdirectory() #文件夹路径
Filepath = filedialog.askopenfilename() #文件路径
(path,filename)=os.path.split(Filepath) #路径和文件名拆分
#去掉扩展名.jpg使用filename[:-4]
img = cv2.imread(filepath)
#『高』(height)『宽』(width)
height,width,channels = img.shape
#注意:如果是灰度图会报错,此时img.shape只包含两个值img.shape[0]和img.shape[1]
#原图1920*1080尺寸(电脑右键属性详细信息)
#print(img.shape) (1080,1920,3)
#裁成 120*90 共计16*12=192张小图
count=0
for i in range(12):
for j in range(16):
small=image[i*90:(i+1)*90,j*120:(j+1)*120, :]
#注意:如果漏掉上面的,:则变为单通道的图
count+=1
cv2.imwrite(imagepath + "/" + 'R' + '%d.jpg' % count, small)
print(count)
# 第16号图为第一行右上角
opencv-python 画未填充矩形
问题来源:opencv官方文档-把鼠标当画笔
解决方案:stackoverflow论坛:drawing rectangle in openCV python
import cv2
ref_point = []
def shape_selection(event, x, y, flags, param):
# grab references to the global variables
global ref_point, crop
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being performed
if event == cv2.EVENT_LBUTTONDOWN: #检测鼠标左键是否按下
ref_point = [(x, y)]
# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates and indicate that
# the cropping operation is finished
ref_point.append((x, y))
# draw a rectangle around the region of interest
cv2.rectangle(image, ref_point[0], ref_point[1], (255, 0, 0), 1)#蓝色画笔
# 注意:如果读入的图的是单通道的,则画笔只会出现白色
cv2.imshow("image", image)
image=cv2.imread(Filepath)
clone = image.copy()
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.setMouseCallback("image", shape_selection)
while True:
# display the image and wait for a keypress
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.imshow("image", image)
key = cv2.waitKey(1) & 0xFF
# press 'r' to reset the window 重画
if key == ord("r"):
image = clone.copy()
# if the 'c' key is pressed, break from the loop 退出
elif key == ord("c"):
break
cv2.imwrite('A.jpg', image)#保存image
# close all open windows
cv2.destroyAllWindows()