一、不同顏色下用python實現摳圖
# opencv模塊
import cv2
import numpy as np
# Step1. 加載圖像
img = cv2.imread('D:\\untitled\\aa\\img.png')
# Step2. 創建掩模、背景圖和前景圖
# mask返回一堆0,1,2,3的數組,shape[:2]形狀切分寬和高,zeros創建0,0,0的數組
mask = np.zeros(img.shape[:2], np.uint8) # 創建大小相同的掩模
bgdModel = np.zeros((1,65), np.float64) # 創建背景圖像
fgdModel = np.zeros((1,65), np.float64) # 創建前景圖像
# Step3. 初始化矩形區域
# 這個矩形必須完全包含前景(相當於這里的梅西)
# rect = (50,50,450,290)
# rect = (275, 120, 170, 320)
# rect = (x,y,w,h) x:左邊距,y:上邊距,w:寬,h:高
rect = (60,110,300,300)
# Step4. GrubCut算法,迭代5次
# mask的取值為0,1,2,3
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) # 迭代5次
# cv2.GC_INIT_WITH_RECT:默認為0,表示框出的矩形圖案
# Step5. mask中,值為2和0的統一轉化為0, 1和3轉化為1
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:,:,np.newaxis] # np.newaxis 插入一個新維度,相當於將二維矩陣擴充為三維
# cv2.imshow("dst", img)
cv2.waitKey(0)
cv2.imwrite(r"D:\untitled\aa\da.png",img)
二、同一種顏色下用python實現摳圖
from PIL import Image
i = 1
j = 1
imgPath = r"D:\untitled\aa\test.png"#.jpeg";
# faZhi = 70#綠色
#imgPath = "/Users/guoanguan/Desktop/kouTu/beiKou.jpeg"
#faZhi = 5#白色
img = Image.open(imgPath)#讀取系統的內照片
img = img.convert('RGBA')
print (img.size)#打印圖片大小
print (img.getpixel((4,4)))
width = img.size[0]#長度
height = img.size[1]#寬度
for i in range(0,width):#遍歷所有長度的點
for j in range(0,height):#遍歷所有寬度的點
data = (img.getpixel((i,j)))#打印該圖片的所有點
#print (data)#打印每個像素點的顏色RGBA的值(r,g,b,alpha)
#print (data[0])#打印RGBA的r值
#摳掉白色
# targetColor = [245, 245, 247]
##targetColor = [49, 166, 64]
# if isEqualNumbers( data[0], targetColor[0]) and isEqualNumbers( data[1],targetColor[1]) and isEqualNumbers( data[2],targetColor[2]):
# img.putpixel((i,j), (0,0,0,0))
#摳掉綠色
if data[0] < data[1] and data[2] < data[1] and data[1] > 100:
img.putpixel((i,j), (0,0,0,0))
# if (data[0]>=170 and data[1]>=170 and data[2]>=170):#RGBA的r值大於170,並且g值大於170,並且b值大於170
# img.putpixel((i,j),(234,53,57,255))#則這些像素點的顏色改成大紅色
#img = img.convert("RGB")#把圖片強制轉成RGB
print(data)
print(img.putpixel)
img.save("resul.png")#保存修改像素點后的圖片