PyOpenCL图像处理:均值灰度化
2018-02-27 00:00
501 查看
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import numpy as np import pyopencl as cl import cv2 from PIL import Image def RoundUp(groupSize, globalSize): r = globalSize % groupSize; if r == 0: return globalSize else: return globalSize + groupSize - r # 创建Context # 如果有多个设备,则会提示选择 ctx = cl.create_some_context() # 创建CommandQueue queue = cl.CommandQueue(ctx) mf = cl.mem_flags # 通过字符串内容编译OpenCL的Program prg = cl.Program(ctx, """ __kernel void gray_avg_filter(__read_only image2d_t input, __write_only image2d_t output){ const sampler_t sampler = CLK_FILTER_NEAREST | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE; int2 size = get_image_dim(input); int2 coord = (int2)(get_global_id(0),get_global_id(1)); float4 pixel = read_imagef(input,sampler,coord); pixel.x = pixel.y = pixel.z = (pixel.x + pixel.y + pixel.z) / 3.0f; write_imagef(output,coord,pixel); } """).build() # 打开图片文件 src1 = Image.open('temp/images/f1.png') dist = Image.new('RGBA',(640,480),(255,255,255)) # OpenCL处理的图片文件格式RGBA,unit8 imageFormat = cl.ImageFormat(cl.channel_order.RGBA,cl.channel_type.UNSIGNED_INT8) # 将图片从Host复制到Device img1 = cl.Image(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR,imageFormat,src1.size,None,src1.tobytes()) output = cl.Image(context=ctx,flags=mf.WRITE_ONLY,format=imageFormat,shape=src1.size) # 根据图片大小定义WorkSize localWorkSize = ( 8, 8 ) globalWorkSize = ( RoundUp(localWorkSize[0], src1.size[0]), RoundUp(localWorkSize[1], src1.size[1])) # 执行Kernel prg.gray_avg_filter(queue,globalWorkSize,localWorkSize,img1,output) buffer = np.zeros(src1.size[0] * src1.size[1] * 4, np.uint8) origin = ( 0, 0, 0 ) region = ( src1.size[0], src1.size[1], 1 ) # 将处理好的图片从设备复制到HOST cl.enqueue_read_image(queue, output, origin, region, buffer).wait() # 保存图片 dist = Image.frombytes("RGBA",src1.size, buffer.tobytes()) dist.save('temp/images/cl-output.png') dist.show()
相关文章推荐
- PyOpenCL图像处理:RGB图像边缘检测
- PyOpenCL图像处理:卡通效果
- PyOpenCL图像处理:Box模糊
- 图像处理之快速均值模糊(Box Blur)
- .NET Core 图像处理(图像二值化,图像灰度化,图像灰度反转)
- 彩色图像的灰度化处理
- opencv3中图像灰度化处理(手动编写处理函数实现)
- 第6章 图像处理_6.1线性滤波(方框、均值、高斯滤波)
- 图像处理中聚类分析算法---C均值算法实现
- 图像处理——灰度化、二值化、膨胀算法、腐蚀算法以及开运算和闭运算
- 【图像处理】图像滤波去噪声——均值滤波、中值滤波、对称均值滤波 低通滤波 高通滤波(opencv)
- C#数字图象处理之图像灰度化方法
- 图像处理(二)opencv处理图像二值化,灰度化等
- Python-OpenCV 处理图像(六)(七)(八):对象识别 图像灰度化处理 图像二值化处理
- 彩色图像的灰度化处理
- 转载:发个MatLab 自编的 均值滤波、中值滤波、高斯滤波 图像处理函数
- Win8 Metro(C#)数字图像处理--3.1图像均值计算
- 图像处理的灰度化和二值化(转)
- 灰度图像--图像分割 阈值处理之迭代均值阈值
- 基于MATLAB图像处理的中值滤波、均值滤波以及高斯滤波的实现与对比