PIL.Image转换成OpenCV格式:
import cv2
from PIL import Image
import numpy
image = Image.open("plane.jpg")
image.show()
img = cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)
cv2.imshow("OpenCV",img)
cv2.waitKey()
cv2.destroyAllWindows()
OpenCV转换成PIL.Image格式:
import cv2
from PIL import Image
import numpy
img = cv2.imread("plane.jpg")
cv2.imshow("OpenCV",img)
image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
image.show()
cv2.waitKey()
cv2.destroyAllWindows()
像素遍历(代码有问题,跑不通,望各位不吝赐教)
import numpy as np
from PIL import Image
def inverse3(img):
w,h= img.size
for x in range(w):
for y in range(h):
pix = img.getpixel((x, y))
R = 255 - pix[0]
G = 255 - pix[1]
B = 255 - pix[2]
img.putpixel((x, y),(R,G,B))
return img
def inverse4(img):
w, h = img.size
pixels = img.load()
print('pixels',type(pixels)) # <class 'PixelAccess'>
for x in range(w):
for y in range(h):
R = 255 - pixels[x, y][0]
G = 255 - pixels[x, y][1]
B = 255 - pixels[x, y][2]
pixels[x, y] = (R,G,B)
return pixels
def inverse5(img):
source = img.split()
R, G, B = 0, 1, 2
source[R].point(lambda i: 255-i)
source[G].point(lambda i: 255-i)
source[B].point(lambda i: 255-i)
img = Image.merge(img.mode, source)
return img
def inverse6(img):
w, h = img.size
pixels = list(img.getdata()) #[(224,232,125),(169,148,245)...]
imgNew = Image.new("RGB", (w,h))
imgNew.putdata(data=pixels)
imgNew.show()
return imgNew
if __name__ == '__main__':
imgpath = r'C:\Users\SongpingWang\Desktop\piaoju\201920100013253001_30302_01.jpg'
image = cv2.imread(imgpath)
# 考虑到需要使用opencv里的算法,所以用opencv打开图片,不过这里暂时没用到。
image= cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
imagePIL = Image.fromarray(image)
inverse3(imagePIL)
inverse4(imagePIL)
inverse5(imagePIL)
inverse6(imagePIL)