# coding: utf8 from PIL import Image
img = Image.open("img.jpg") print img.size
print img.format
# coding: utf8 from PIL import Image
img = Image.open("img.jpg") print img.size
print img.format
转载于:https://www.cnblogs.com/zhangtianyuan/p/7306588.html
import cv2 import numpy as py # 获取图像的信息 def get_img_info(src): height = src.shape[0] width = src.shape[1] channels = src.shape[2] print('长度:%d 宽度:%d 通道:%d' % (height, width, channels)) # 滑条的回调函数 def nothing(x): pass img = cv2.imread('football.png') cv2.rectangle(img, (100, 300), (188, 368), (0, 0, 255), 1) width1 = 601 height1 = 375 dim = (width1, height1) # 修改图像的大小,使两幅图的大小相同 img2 = cv2.imread('tree.jpg') img2 = cv2.resize(img2, dim, interpolation=cv2.INTER_AREA) # 修改图像大小 cv2.namedWindow('input img', cv2.WINDOW_AUTOSIZE) cv2.createTrackbar('bar', 'input img', 0, 10, nothing) # 创建滑条来修改图像融合度 cv2.imshow('input img', img) get_img_info(img) get_img_info(img2) while(1): tmp = cv2.getTrackbarPos('bar', 'input img') dst = cv2.addWeighted(img2, float(tmp/10), img, float(1-(tmp/10)), 0) # 图像混合 cv2.imshow('input img', dst) c = cv2.waitKey(1) # 不能为0,为0的话会等待一个输入直到有内容输入 if c == 27: break # cv2.destroyAllWindows()
- 获取canvas,img元素
- 使用canvas的getImageData方法获取像素数据
canvas的getImageData方法
getImageData() 方法返回 ImageData 对象,该对象拷贝了画布指定矩形的像素数据。
对于 ImageData 对象中的每个像素,都存在着四方面的信息,即 RGBA 值:
R - 红色 (0-255)
G - 绿色 (0-255)
B - 蓝色 (0-255)
A - alpha 通道 (0-255; 0 是透明的,255 是完全可见的)
color/alpha 以数组形式存在,并存储于 ImageData 对象的 data 属性中
参数
x 开始复制的左上角位置的 x 坐标。 y 开始复制的左上角位置的 y 坐标。 width 将要复制的矩形区域的宽度。 height 将要复制的矩形区域的高度。 实现
const canvas = this.refs.wheelbg const img = document.getElementById('tplWheelBg') _setWheelBgtcMainTonal = (canvas, img) => { canvas.width = img.width canvas.height = img.height let context = canvas.getContext('2d') context.drawImage(img, 0, 0) // 获取像素数据 let data = context.getImageData(0, 0, img.width, img.height).data console.log(data); let r = 0, g = 0, b = 0 // 取所有像素的平均值 for (let row = 0; row < img.height; row++) { for (let col = 0; col < img.width; col++) { r += data[(img.width * row + col) * 4] g += data[(img.width * row + col) * 4 + 1] b += data[(img.width * row + col) * 4 + 2] } } // 求取平均值 r /= img.width * img.height g /= img.width * img.height b /= img.width * img.height // 将最终的值取整 r = Math.round(r) g = Math.round(g) b = Math.round(b) //rgb转16进制 位运算 const color = ((r << 16) | (g << 8) | b).toString(16) return color }
获取图片的信息
import cv2 as cv img = cv.imread('girl.jpg') imginfo = img.shape print(imginfo) height = imginfo[0] width = imginfo[1] mode = imginfo[2] #此图片mode值为3,代表一个像素点由3中颜色组成
压缩图片
import cv2 img = cv.imread('girl.jpg') imginfo = img.shape print(imginfo) height = imginfo[0] width = imginfo[1] mode = imginfo[2] #此图片mode值为3,代表一个像素点由3中颜色组成 datheight = int(height*0.5) datwidth = int(width*0.5) datimg = cv.resize(img, (datwidth, datheight)) cv2.imshow('image', datimg) cv.waitKey()