`
schi
  • 浏览: 205866 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

convert color image to grayscale with pyopencl(example code)

阅读更多
grayscale.py
import pyopencl as cl
import sys
import Image
import numpy

def RoundUp(groupSize, globalSize):
	r = globalSize % groupSize;
	if r == 0:
		return globalSize;
	else:
		return globalSize + groupSize - r;

def main():
	
	imageObjects = [ 0, 0 ]
			
	if len(sys.argv) != 3:
		print "USAGE: " + sys.argv[0] + " <inputImageFile> <outputImageFile>"
		return 1
	
	# create context and command queue
	ctx = cl.create_some_context()
	queue = cl.CommandQueue(ctx)
	
	# load image
	im = Image.open(sys.argv[1])
	if im.mode != "RGBA":
		im = im.convert("RGBA")
	imgSize = im.size
	buffer = im.tostring()

	
	# Create ouput image object
	clImageFormat = cl.ImageFormat(cl.channel_order.RGBA, 
								cl.channel_type.UNSIGNED_INT8)
	imageObjects[0] = cl.Image(ctx,
								cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR,
								clImageFormat,
								imgSize,
								None,
								buffer)
	imageObjects[1] = cl.Image(ctx,
							cl.mem_flags.WRITE_ONLY,
							clImageFormat,
							imgSize)

	# load the kernel source code
	kernelFile = open("grayscale.cl", "r")
	kernelSrc = kernelFile.read()

	# Create OpenCL program
	program = cl.Program(ctx, kernelSrc).build()
	
	# Call the kernel directly
	localWorkSize = ( 16, 16 )
	globalWorkSize = ( RoundUp(localWorkSize[0], imgSize[0]),
					RoundUp(localWorkSize[1], imgSize[1]) )

	program.rgbaToGrayscale(queue,
							globalWorkSize,
							localWorkSize,
							imageObjects[0],
							imageObjects[1])
		
	# Read the output buffer back to the Host
	buffer = numpy.zeros(imgSize[0] * imgSize[1] * 4, numpy.uint8)
	origin = ( 0, 0, 0 )
	region = ( imgSize[0], imgSize[1], 1 )
	
	cl.enqueue_read_image(queue, imageObjects[1],
						origin, region, buffer).wait()
	
	print "Executed program succesfully."
	
	# Save the image to disk
	gsim = Image.fromstring("RGBA", imgSize, buffer.tostring())
	gsim.save(sys.argv[2])
    
main()


grayscale.cl
const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | 
						  CLK_ADDRESS_CLAMP_TO_EDGE | 
						  CLK_FILTER_NEAREST;

__kernel void rgbaToGrayscale(__read_only image2d_t srcImg,
                              __write_only image2d_t dstImg)
{
	// Converts RGBA image to gray scale intensity using the following formula: 
	// I = 0.2126 * R + 0.7152 * G + 0.0722 * B

	int2 coord = (int2) (get_global_id(0), get_global_id(1));
	int width = get_image_width(srcImg);
	int height = get_image_height(srcImg);

	if (coord.x < width && coord.y < height)
	{
		uint4 color = read_imageui(srcImg, sampler, coord);
		float luminance = 0.2126f * color.x + 0.7152f * color.y + 0.0722f * color.z;
		color.x = color.y = color.z = (uint)luminance;
		
		// Write the output value to image
		write_imageui(dstImg, coord, color);
	}
}






  • 大小: 1.3 MB
  • 大小: 5.7 MB
分享到:
评论

相关推荐

    Reversible Data Hiding in Color Image with Grayscale Invariance

    《可逆数据隐藏在彩色图像中的灰度不变性》是一篇关于数字图像处理领域的研究论文,主要探讨了在彩色图像中实现数据隐藏的方法,并确保在数据提取后图像能恢复到原始状态,同时保持灰度级不变性。...

    RGB2Gray.rar_grayscale_rgb to grayscale

    convert rgb to grayscale

    ImageMagick图片批量处理

    -color-matrix matrix apply color correction to the image -contrast enhance or reduce the image contrast -contrast-stretch geometry improve contrast by `stretching' the intensity range -convolve ...

    Image-To-Grayscale.rar_grayscaling

    this is code for basic processing in image processig suc as grayscaling, negatif picture, and others.

    Drawing an image in grayscale画位图到一个灰色刻度中(5KB)

    首先,让我们理解“Drawing an image in grayscale”这个概念。当我们要在屏幕上或保存为文件时,将彩色图像转换为灰度,我们需要将每个像素的红、绿、蓝(RGB)分量合并成一个单一的亮度值。这可以通过多种方法完成,...

    Fading from color to grayscale and vice-versa淡色效果(7KB)

    在给定的资源中,"grayscale_fadein.shtml.htm"可能是一个HTML页面,它可能使用JavaScript或CSS3的动画效果来展示这种过渡。JavaScript可以访问DOM中的图像元素,动态修改其像素数据,实现淡入淡出效果。CSS3的`...

    A subset of the STL10 Dataset (stlSubset.zip)

    You can just combine the intensities from all the color channels for the pixels into one long vector, as if you were working with a grayscale image with 3x the number of pixels as the original image.

    基于Matlab的图像的数据分析.pdf

    After the image is loaded, it may be necessary to identify and convert the image format, which can be done using functions like isgray and rgb2gray to check if the image is grayscale or convert it to ...

    LCD image Converter 2.1老朽痴拙汉化版(位图生成器qt)

    Monochrome, grayscale, color; With vertical and horizontal orientation of bytes; 8, 16, 24, 32-bit data; 1...24 bits per pixel; RLE compression; With different display controllers, not limited by one ...

    Enhancing the Quality of Grayscale Images

    ### 图像增强技术:基于多组件的直方图均衡化 #### 概述 随着数字图像处理技术的发展,提升图像质量成为了许多应用领域中的一个重要环节。图像增强是提高图像视觉效果的重要手段之一,尤其在消费电子、医疗成像、...

    IconLover 5.17 Portable

    » Create and edit icons in standard and custom sizes, with color depth up to 32-bit True Color » Make stylish icons from your images » Paint images with gradients and fills » Create multi-layer ...

    Gray-Image.zip_PByteArray_Refresh_ Refresh_procedure Grayscale

    procedure GrayScale(const Image:TImage) var BytesPerScan: Integer iWidth, iHeight: Integer pScanLine: pByteArray R,G,B: Byte begin try BytesPerScan := Abs(Integer(Image.Picture.Bitmap....

    CSS style filter

    filter: DropShadow(Color=color, OffX=offX, OffY=offY, Positive=positive); } ``` - **参数**: - `Color`:阴影颜色,格式为`#rrggbb`。 - `OffX`:水平偏移量。 - `OffY`:垂直偏移量。 - `Positive`:...

    Ampare Grayscale Image To Color-crx插件

    语言:English (United States) 将任何灰度图像转换为彩色 Ampare灰度图像到彩色是一个简单易用的Chrome扩展程序,可将那些复杂的功能隐藏在后面。 只需单击一下按钮,它就可以使用深度学习神经元网络人工智能将任何...

    matlab_提取糖尿病视网膜病变眼底图像上硬性渗出。通过转为灰度图,再进行形态学处理、去背景、阈值分割,最终把硬性渗出区域标记

    提取糖尿病视网膜病变眼底... The color image to grayscale on grayscale morphological processing to the background, threshold segmentation, ultimately on the original hard exudates area marked in green.)

    grayscale.js.zip

    《grayscale.js.zip:实现全网站灰度效果的JavaScript代码》 在网页设计中,有时候我们需要为网站添加一种特殊的视觉效果,比如在特定的纪念日或活动期间将整个网站变为灰度模式,以表达敬意或突出特定内容。...

    灰度图Gray Scale Image 定义

    灰度图,也被称为灰阶图像,是一种特殊类型的图像,其中每个像素的色彩信息只用一个亮度级别来表示,这个级别通常是从纯黑到纯白之间的连续色调。在灰度图像中,没有颜色信息,只有不同深浅的灰色,因此,这种图像的...

    用c++灰度图象显示

    cv::imshow("Color Image", colorImage); cv::namedWindow("Grayscale Image", cv::WINDOW_NORMAL); cv::imshow("Grayscale Image", grayImage); ``` 6. **等待用户按键并关闭窗口**: 使用`cv::waitKey()`函数...

    moviepy音视频剪辑VideoClip类fl_image方法及参数image_func的功能介绍.rar

    return image.convert('L') video = VideoClip("my_video.mp4") grayscale_video = video.fl_image(apply_grayscale) ``` 在这个例子中,`apply_grayscale`函数将输入的彩色图像转换为灰度,然后`fl_image`将这个...

Global site tag (gtag.js) - Google Analytics