fork download
  1. import pyopencl as cl
  2. import numpy as np
  3. from PIL import Image
  4.  
  5. def main():
  6.  
  7. image = Image.open('my_image.png')
  8.  
  9. (width, height) = image.size
  10.  
  11. if image.mode != 'RGB':
  12. image = image.convert('RGB')
  13.  
  14. intType = np.dtype(np.int)
  15.  
  16. imarr = np.array(image, dtype = intType)
  17.  
  18. platform = cl.get_platforms()[0]
  19. device = platform.get_devices()[0]
  20.  
  21. ctx = cl.Context(devices = [device])
  22. queue = cl.CommandQueue(ctx)
  23.  
  24. mf = cl.mem_flags
  25.  
  26. imarr_d = cl.Buffer(ctx, mf.READ_ONLY, imarr.nbytes)
  27. cl.enqueue_copy(queue, imarr_d, imarr, is_blocking = True)
  28.  
  29. result = np.zeros([width, height], dtype = intType)
  30. result_d = cl.Buffer(ctx, mf.READ_WRITE, result.nbytes)
  31. cl.enqueue_copy(queue, result_d, result, is_blocking = True)
  32.  
  33. code = '''
  34.  
  35. __kernel void has_rgb_value(
  36. __global int * imarr_d,
  37. __global int * result_d)
  38. {
  39. int x = get_global_id(0);
  40. int y = get_global_id(1);
  41.  
  42. int i = x * %(height)d * 3 + y * 3;
  43.  
  44. if (imarr_d[i + 0] == %(red)d &&
  45. imarr_d[i + 1] == %(green)d &&
  46. imarr_d[i + 2] == %(blue)d)
  47. {
  48. result_d[x * %(height)d + y] = 1;
  49. }
  50. }
  51.  
  52. __kernel void reduce(
  53. __global int * result_d)
  54. {
  55. int i = get_global_id(0);
  56.  
  57. for (int j = 1; j < %(height)d; j ++)
  58. {
  59. result_d[i * %(height)d + 0] += result_d[i * %(height)d + j];
  60. }
  61. }
  62.  
  63. ''' % {
  64. 'red' : 255,
  65. 'green' : 0,
  66. 'blue' : 255,
  67. 'height' : height
  68. }
  69.  
  70. program = cl.Program(ctx, code).build()
  71.  
  72. program.has_rgb_value(
  73. queue, (width, height), None,
  74. imarr_d, result_d
  75. ).wait()
  76.  
  77. program.reduce(
  78. queue, (width, ), None,
  79. result_d
  80. ).wait()
  81.  
  82. cl.enqueue_copy(queue, result, result_d, is_blocking = True)
  83.  
  84. for i in range(1, width):
  85. result[0, 0] += result[i, 0];
  86.  
  87. print result[0, 0]
  88.  
  89. if __name__ == '__main__':
  90. main()
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty