-
-
Save jubicode/9461398a0fab22155b9da80f4fd5bfca to your computer and use it in GitHub Desktop.
Select By Color (Blender)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import bpy | |
| from mathutils import Color | |
| bl_info = { | |
| 'name': 'Select By Color', | |
| 'author': 'Tamas Kemenczy, updated for 2.8 by Piotr Zgodziński', | |
| 'version': (0, 2), | |
| 'blender': (2, 80, 3), | |
| 'location': 'View3D > Specials > Select By Color', | |
| 'description': 'Select all faces with the same vertex color of the selected face', | |
| 'category': 'Mesh' | |
| } | |
| def select_by_color(obj, threshold=0.01): | |
| # get wierd behavior/errors when in editmode | |
| bpy.ops.object.editmode_toggle() | |
| if not hasattr(obj.data.vertex_colors.active, 'data'): | |
| return | |
| colors = obj.data.vertex_colors.active.data | |
| selected_polygons = list(filter(lambda p: p.select, obj.data.polygons)) | |
| if len(selected_polygons): | |
| p = selected_polygons[0] | |
| r = g = b = 0 | |
| for i in p.loop_indices: | |
| r1, g1, b1, a1 = colors[i].color | |
| r += r1 | |
| g += g1 | |
| b += b1 | |
| r /= p.loop_total | |
| g /= p.loop_total | |
| b /= p.loop_total | |
| target = Color((r, g, b)) | |
| for p in obj.data.polygons: | |
| r = g = b = 0 | |
| for i in p.loop_indices: | |
| r1, g1, b1, a1 = colors[i].color | |
| r += r1 | |
| g += g1 | |
| b += b1 | |
| r /= p.loop_total | |
| g /= p.loop_total | |
| b /= p.loop_total | |
| source = Color((r, g, b)) | |
| if (abs(source.r - target.r) < threshold and | |
| abs(source.g - target.g) < threshold and | |
| abs(source.b - target.b) < threshold): | |
| p.select = True | |
| bpy.ops.object.editmode_toggle() | |
| class SelectByColor(bpy.types.Operator): | |
| bl_label = 'Select By Color' | |
| bl_idname = 'mesh.select_by_color' | |
| bl_options = {'REGISTER', 'UNDO'} | |
| threshold: bpy.props.FloatProperty(name='Threshold', default=0.01, min=0.001, max=1.0, step=1) | |
| @classmethod | |
| def poll(cls, context): | |
| obj = context.active_object | |
| return (obj and obj.type == 'MESH') | |
| def execute(self, context): | |
| select_by_color(context.active_object, self.threshold) | |
| return {'FINISHED'} | |
| def menu_func(self, context): | |
| self.layout.operator(SelectByColor.bl_idname, text='Select By Color') | |
| def register(): | |
| bpy.utils.register_class(SelectByColor) | |
| bpy.types.VIEW3D_MT_edit_mesh_context_menu.prepend(menu_func) | |
| def unregister(): | |
| bpy.utils.unregister_class(SelectByColor) | |
| bpy.types.VIEW3D_MT_edit_mesh_context_menu.remove(menu_func) | |
| if __name__ == "__main__": | |
| register() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment