Skip to content

Instantly share code, notes, and snippets.

@niittymaa
Forked from zeffii/more_image_manipulation.py
Created February 11, 2020 08:07
Show Gist options
  • Save niittymaa/af8bd64ac61a842e273b62d16f99b587 to your computer and use it in GitHub Desktop.
Save niittymaa/af8bd64ac61a842e273b62d16f99b587 to your computer and use it in GitHub Desktop.
more_image_manipulation.py
import bpy
D = bpy.data
test_file = 'firefly_test_pattern_2.tga'
# my test image is 24 px wide and 7 px heigh
# download here if you want to test along.
#alias if you can
img = D.images[test_file]
# operate on a copy, for fast access
pxs = pixels = list(img.pixels)
w = width = img.size[0]
h = height = img.size[1]
num_pixels = len(pxs)
# grouped_list = [pxs[ipx:ipx+4] for ipx in range(0, num_pixels, 4)]
gl = grouped_list = [pxs[i:i+4] for i in range(num_pixels)[::4]]
print(gl)
# row, col
def idx_to_co(idx, width):
r = int(idx / width)
c = idx % width
return r, c
def co_to_idx(r, c, width):
return r * width + c
# 0,0 is first pixel bottom left, index should be 0
print( co_to_idx(0, 0 ,w) ) # >>> 0
# 1,1 is 1 px up and 1px to the right, the index should be 24+1
print( co_to_idx(1, 1 ,w) ) # >>> 25
# 6, 23 is top right, because we count from 0. index should be the same
# as the number of grouped pixels in the image minus one. ( 24*7)-1
print( co_to_idx(6,23, w) ) # >>> 167
# and the other way around too
# idx 0 -> coordinate 0 ,0
# idx 25 -> coordinate 1 ,1
# idx 167 -> coordinate 6,23
print( idx_to_co(0, w) ) # >>> 0, 0
print( idx_to_co(25, w) ) # >>> 1, 1
print( idx_to_co(167, w) ) # >>> 6,23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment