def gerberToPNG(filename, png, pixel_mm=0.1):
    """
    Convert to png.
    Return pixel size in mm.
    """
    try:
        import gerber
    except Exception as e:
        if 'hull' in str(e).lower():
            raise Exception('Module pyhull not found. Try "pip install pyhull"?')
        raise Exception('The gerber module can be found at https://github.com/curtacircuitos/pcb-tools.')
    try:
        from gerber.render import GerberCairoContext
    except Exception as e:
        if 'cairo' in str(e).lower():
            raise Exception('Failed to load gerber.render. Do you have the py2cairo package, which provides the cairo module?')
        raise e

    # Read gerber and Excellon files
    data = gerber.read(filename)
    data.to_metric()
    
    # Rendering context
    ctx = GerberCairoContext(scale=1.0/pixel_mm) # Scale is pixels/mm

    # Create SVG image
    data.render(ctx)
    ctx.dump(png)
    return png, np.mean(data.size) / np.mean(ctx.size_in_pixels)
Beispiel #2
0
def gerberToPNG(filename, png, pixel_mm=0.1):
    """
    Convert to png.
    Return pixel size in mm.
    """
    try:
        import gerber
    except Exception as e:
        if 'hull' in str(e).lower():
            raise Exception(
                'Module pyhull not found. Try "pip install pyhull"?')
        raise Exception(
            'The gerber module can be found at https://github.com/curtacircuitos/pcb-tools.'
        )
    try:
        from gerber.render import GerberCairoContext
    except Exception as e:
        if 'cairo' in str(e).lower():
            raise Exception(
                'Failed to load gerber.render. Do you have the py2cairo package, which provides the cairo module?'
            )
        raise e

    # Read gerber and Excellon files
    data = gerber.read(filename)
    data.to_metric()

    # Rendering context
    ctx = GerberCairoContext(scale=1.0 / pixel_mm)  # Scale is pixels/mm

    # Create SVG image
    data.render(ctx)
    ctx.dump(png)
    return png, np.mean(data.size) / np.mean(ctx.size_in_pixels)
Beispiel #3
0
def read_s8tp_file(file_path, img_name='test-gerber.png'):
    print('transfer gerber to image...')
    gerber_obj = gerber.read(file_path)
    ctx = GerberCairoContext()
    gerber_obj.render(ctx)
    ctx.dump(img_name)
    # img_ram = cv2.imread('test-gerber.png')
    # os.remove('test-gerber.png')
    return img_name
def is_non_pth_ring_making(file_dir):
    ctx = GerberCairoContext()
    non_pth_gerber_file = file_dir + 'npth.drl'
    top_gerber_file = file_dir + 'top.gbr'
    top_primitives = get_all_primitives_from_gerber(top_gerber_file)
    non_pth_primitives = get_all_primitives_from_gerber(non_pth_gerber_file)
    shape_primitives = get_single_shape_from_gerber(top_primitives, Circle)
    Line_primitives = get_single_shape_from_gerber(top_primitives, Line)
    bounding_box = get_bounding_box_of_multiply([p.bounding_box for p in top_primitives])
    ctx.set_bounds(bounding_box)
    ctx._paint_background()
    ctx._new_render_layer()
    count = 0
    dis = []
    for non_pth_primitive in non_pth_primitives:
        (x, y) = non_pth_primitive.position
        if non_pth_primitive.position == (2.067, 2.392):
            print('ppppppp')
        for shape_primitive in shape_primitives:
            (x1, y1) = shape_primitive.position
            if ("%.3f" % x) == ("%.3f" % x1) and ("%.3f" % y) == ("%.3f" % y1):
                if shape_primitive.radius > non_pth_primitive.radius:
                    count = count + 1
                    dis.append(shape_primitive.radius - non_pth_primitive.radius)
                    if shape_primitive.position == (2.066929, 2.391732) \
                            and non_pth_primitive.position == (2.067, 2.392):
                        if shape_primitive.radius == 0.019685:
                            draw_bounding_box_of_char(Line_primitives[0], 1, shape_primitive.bounding_box, ctx)
                        print('kkkkkkkkk', shape_primitive.radius, shape_primitive.bounding_box)
                    if shape_primitive.radius - non_pth_primitive.radius < 0.01:
                        print('hhhhh', shape_primitive.radius, non_pth_primitive.radius, count)
                        print(shape_primitive.position, non_pth_primitive.position)
                        # draw_bounding_box_of_char(Line_primitives[0], 1, non_pth_primitive.bounding_box, ctx)
                        # ctx.render(non_pth_primitive.bounding_box)
                    else:
                        ctx.render(shape_primitive)

    ctx._flatten()
    ctx.dump('shapepth2.png')
    dis.sort()
    print(dis)
    print(count, len(non_pth_primitives))
    if count > 0:
        return True
    return False
def gerberToPNG(filename, png, pixel_mm=0.1):
    """
    Convert to png.
    Return pixel size in mm.
    """
    import gerber
    from gerber.render import GerberCairoContext

    # Read gerber and Excellon files
    data = gerber.read(filename)
    data.to_metric()
    
    # Rendering context
    ctx = GerberCairoContext(scale=1.0/pixel_mm) # Scale is pixels/mm

    # Create SVG image
    data.render(ctx)
    ctx.dump(png)
    return png, np.mean(data.size) / np.mean(ctx.size_in_pixels)
def gerberToPNG(filename, png, pixel_mm=0.1):
    """
    Convert to png.
    Return pixel size in mm.
    """
    import gerber
    from gerber.render import GerberCairoContext

    # Read gerber and Excellon files
    data = gerber.read(filename)
    data.to_metric()

    # Rendering context
    ctx = GerberCairoContext(scale=1.0 / pixel_mm)  # Scale is pixels/mm

    # Create SVG image
    data.render(ctx)
    ctx.dump(png)
    return png, np.mean(data.size) / np.mean(ctx.size_in_pixels)
def draw_all_primitives1(index_span_for_primitives,
                         all_lines_and_arc_primitives,
                         all_primitives,
                         output_dir,
                         bounding_box=None):
    if not os.path.exists(output_dir): os.makedirs(output_dir)
    ctx = GerberCairoContext()
    if bounding_box is None:
        bounding_box = get_bounding_box_of_multiply(
            [p.bounding_box for p in all_lines_and_arc_primitives])

    background_height = 20
    background_width = 20

    original_width = bounding_box[0][1] - bounding_box[0][0]
    original_height = bounding_box[1][1] - bounding_box[1][0]
    need_rotate = False
    if original_width > original_height:
        need_rotate = True
    ratio = min(background_height / original_height,
                background_width / original_width)
    (min_x, max_x), (min_y, max_y) = bounding_box
    new_bounding_box = (min_x * ratio, max_x * ratio), (min_y * ratio,
                                                        max_y * ratio)
    ctx.set_bounds(new_bounding_box)
    ctx._paint_background()
    ctx._new_render_layer()

    for i in range(len(index_span_for_primitives) - 1):
        line_index = index_span_for_primitives[i]
        begin = line_index[0]
        end = line_index[1]
        lines = all_lines_and_arc_primitives[begin:end + 1]
        small_bounding_box = get_bounding_box_of_multiply(
            [p.bounding_box for p in lines])
        draw_bounding_box_of_char(lines[0], ratio, small_bounding_box, ctx)
        if True:
            for p in lines:
                s_x, s_y = p.start
                p.start = s_x * ratio, s_y * ratio
                e_x, e_y = p.end
                p.end = e_x * ratio, e_y * ratio

                if isinstance(p, Arc):
                    c_x, c_y = p.center
                    p.center = c_x * ratio, c_y * ratio
                ctx.render(p)
    '''
        count = 0
        print('hhhhhh', len(all_primitives))
        for p in all_primitives:
        
            s_x, s_y = p.start
            p.start = s_x * ratio, s_y * ratio
            e_x, e_y = p.end
            p.end = e_x * ratio, e_y * ratio

            if isinstance(p, Arc):
                c_x, c_y = p.center
                p.center = c_x * ratio, c_y * ratio
            
            if not isinstance(p, Line):  # or isinstance(p, gerber.primitives.Region)):
                # ctx.render(p)
                count = count + 1
                # print(type(p), p.bounding_box, count, len(p.primitives))
            '''
    ctx._flatten()
    filename_with_coordination = append_filename_with_coordination(
        '{}-{}.png'.format(0, 0), bounding_box)
    image_path = os.path.join(output_dir, filename_with_coordination)
    ctx.dump(image_path)
    return filename_with_coordination
def generate_some_primitives(primitives,
                             output_dir,
                             filename,
                             bounding_box=None):
    if len(primitives) == 0: return

    if not os.path.exists(output_dir): os.makedirs(output_dir)

    ctx = GerberCairoContext()

    if bounding_box is None:
        bounding_box = get_bounding_box_of_multiply(
            [p.bounding_box for p in primitives])

    # standard_width = 1
    # standard_height = 1.4

    background_height = 2
    background_width = 2

    original_width = bounding_box[0][1] - bounding_box[0][0]
    original_height = bounding_box[1][1] - bounding_box[1][0]

    need_rotate = False

    if original_width > original_height:
        # if we find the orientation is left-to-right, we set the height smaller than height
        # standard_height, standard_width = standard_width, standard_height
        need_rotate = True

    ratio = min(background_height / original_height,
                background_width / original_width)

    (min_x, max_x), (min_y, max_y) = bounding_box
    new_bounding_box = (min_x * ratio, max_x * ratio), (min_y * ratio,
                                                        max_y * ratio)

    ctx.set_bounds(new_bounding_box)

    ctx._paint_background()
    ctx._new_render_layer()

    for p in primitives:
        s_x, s_y = p.start
        p.start = s_x * ratio, s_y * ratio

        e_x, e_y = p.end
        p.end = e_x * ratio, e_y * ratio

        if isinstance(p, Arc):
            c_x, c_y = p.center
            p.center = c_x * ratio, c_y * ratio

        ctx.render(p)

    ctx._flatten()

    filename_with_coordination = append_filename_with_coordination(
        filename, bounding_box)

    image_path = os.path.join(output_dir, '20-' + filename)

    ctx.dump(image_path)

    image = Image.open(image_path)

    if need_rotate:
        image = image.transpose(Image.ROTATE_270)

        # tranposed.show()
        # input('continue?')
        image.save(image_path)

    return filename_with_coordination
Beispiel #9
0
def draw_all_primitives(index_span_for_primitives,
                        all_lines_and_arc_primitives,
                        all_primitives,
                        output_dir,
                        bounding_box=None):
    if not os.path.exists(output_dir): os.makedirs(output_dir)
    ctx = GerberCairoContext()
    if bounding_box is None:
        bounding_box = get_bounding_box_of_multiply(
            [p.bounding_box for p in all_primitives])

    original_width = bounding_box[0][1] - bounding_box[0][0]
    original_height = bounding_box[1][1] - bounding_box[1][0]

    background_height = original_height
    background_width = original_width
    need_rotate = False
    if original_width > original_height:
        need_rotate = True
    ratio = min(background_height / original_height,
                background_width / original_width)
    (min_x, max_x), (min_y, max_y) = bounding_box
    new_bounding_box = (min_x * ratio, max_x * ratio), (min_y * ratio,
                                                        max_y * ratio)
    ctx.set_bounds(new_bounding_box)
    ctx._paint_background()
    ctx._new_render_layer()

    def size_of_box(bounding_box):
        (min_x, max_x), (min_y, max_y) = bounding_box
        return (max_x - min_x) * (max_y - min_y)

    def is_include(p, box1):
        (min_x1, max_x1), (min_y1, max_y1) = box1
        ((min_x2, max_x2), (min_y2, max_y2)) = p.bounding_box
        margin_threshold = (max_x1 - min_x1) / 3
        if min_x1 - margin_threshold <= min_x2 and max_x1 + margin_threshold >= max_x2 \
                and min_y1 - margin_threshold <= min_y2 and max_y1 + margin_threshold >= max_y2:
            return True
        return False

    check_box = []
    count = 0
    box_threshold = 0.001
    size_of_check_box = 0.0121
    checked_sign_nums = 8
    for i in range(len(index_span_for_primitives) - 1):
        line_index = index_span_for_primitives[i]
        begin = line_index[0]
        end = line_index[1]
        lines = all_lines_and_arc_primitives[begin:end + 1]
        small_bounding_box = get_bounding_box_of_multiply(
            [p.bounding_box for p in lines])
        # draw_bounding_box_of_char(lines[0], ratio, small_bounding_box, ctx)
        if abs(size_of_box(small_bounding_box) -
               size_of_check_box) < box_threshold and len(lines) == 4:
            check_box.append(small_bounding_box)
            # draw_bounding_box_of_char(lines[0], ratio, small_bounding_box, ctx)
        # draw_lines(ctx, ratio, lines)
    choose_box = []
    for p in all_primitives:
        for box in check_box:
            if isinstance(p, gerber.primitives.Region) and len(
                    p.primitives) == checked_sign_nums and is_include(p, box):
                count += 1
                ((min_xp, max_xp), (min_yp, max_yp)) = p.bounding_box
                x_min = (min_xp - min_x) / (max_x - min_x)
                x_max = (max_xp - min_x) / (max_x - min_x)
                y_min = (min_yp - min_y) / (max_y - min_y)
                y_max = (max_yp - min_y) / (max_y - min_y)
                cbox = (x_min, x_max), (y_min, y_max)
                choose_box.append(cbox)
                ctx.render(p)
                draw_bounding_box_of_char(lines[0], ratio, box, ctx)

    print('--------', len(choose_box))
    ctx._flatten()
    filename_with_coordination = append_filename_with_coordination(
        '{}-{}.png'.format(0, 0), bounding_box)
    image_path = os.path.join(output_dir, filename_with_coordination)
    ctx.dump(image_path)
    print(image_path)
    return filename_with_coordination
Beispiel #10
0
# Draw the soldermask layer
# ctx.render_layer(mask)

# The default style can be overridden by passing a RenderSettings instance to
# render_layer().
# First, create a settings object:
our_settings = RenderSettings(color=theme.COLORS['white'], alpha=0.85)

# Draw the silkscreen layer, and specify the rendering settings to use
# ctx.render_layer(silk, settings=our_settings)

# Draw the drill layer
# ctx.render_layer(drill)

# Write output to png file
ctx.dump(os.path.join(os.path.dirname(__file__), 'NISHAD_TEST1.png'))

# Load the bottom layers
# copper = load_layer(os.path.join(GERBER_FOLDER, 'bottom_copper.GBL'))
# mask = load_layer(os.path.join(GERBER_FOLDER, 'bottom_mask.GBS'))

# # Clear the drawing
# ctx.clear()

# # Render bottom layers
# ctx.render_layer(copper)
# ctx.render_layer(mask)
# ctx.render_layer(drill)
# ctx.render_layer(silk)

# # Write png file
if not os.path.isdir(os.path.join(os.path.dirname(__file__), 'outputs')):
    os.mkdir(os.path.join(os.path.dirname(__file__), 'outputs'))

for infile in listdir(GERBER_FOLDER):
    if infile.startswith('test'):
        try:
            outfile = os.path.splitext(infile)[0] + '.png'
            if infile.endswith('gbx'):
                layer = gerber_read(os.path.join(GERBER_FOLDER, infile))
                print("Loaded Gerber file: {}".format(infile))
            elif infile.endswith('exc'):
                layer = excellon_read(os.path.join(GERBER_FOLDER, infile))
                print("Loaded Excellon file: {}".format(infile))
            else:
                continue

            # Create a new drawing context
            ctx = GerberCairoContext(1200)
            ctx.color = (80./255, 80/255., 154/255.)
            ctx.drill_color = ctx.color

            # Draw the layer, and specify the rendering settings to use
            layer.render(ctx)

            # Write output to png file
            print("Writing output to: {}".format(outfile))
            ctx.dump(os.path.join(os.path.dirname(__file__), 'outputs', outfile))
        except Exception as exc:
            import traceback
            traceback.print_exc()
def draw_all_primitives(index_span_for_primitives, all_lines_and_arc_primitives, output_dir, bounding_box=None):
    if not os.path.exists(output_dir): os.makedirs(output_dir)
    ctx = GerberCairoContext()
    if bounding_box is None:
        bounding_box = get_bounding_box_of_multiply([p.bounding_box for p in all_lines_and_arc_primitives])

    background_height = 20
    background_width = 20

    original_width = bounding_box[0][1] - bounding_box[0][0]
    original_height = bounding_box[1][1] - bounding_box[1][0]
    need_rotate = False
    if original_width > original_height:
        need_rotate = True
    ratio = min(background_height / original_height, background_width / original_width)
    (min_x, max_x), (min_y, max_y) = bounding_box
    new_bounding_box = (min_x * ratio, max_x * ratio), (min_y * ratio, max_y * ratio)
    # print('ratio', ratio)
    max_area = (max_x - min_x) * (max_y - min_y)

    ctx.set_bounds(new_bounding_box)
    ctx._paint_background()

    ctx._new_render_layer()
    show_char = True

    all_grouped_box = []
    for i in range(len(index_span_for_primitives) - 1):
        line_index = index_span_for_primitives[i]
        begin = line_index[0]
        end = line_index[1]
        lines = all_lines_and_arc_primitives[begin:end + 1]
        if len(lines) >= 2:
            small_bounding_box = get_bounding_box_of_multiply([p.bounding_box for p in lines])
            (x_min, y_min), (x_max, y_max) = small_bounding_box
            # print(abs((x_max - x_min) * (y_max - y_min)))
            # print(abs((x_max - x_min) * (y_max - y_min) / max_area))
            print(max_area)
            print('*' * 20)

            if (x_max - x_min) * (y_max - y_min) / max_area > 0.1:
                print('inside point', (x_max - x_min) * (y_max - y_min))

                all_grouped_box.append(small_bounding_box)
                draw_bounding_box_of_char(lines[0], ratio, small_bounding_box, ctx)
            else:
                print('outside point', (x_max - x_min) * (y_max - y_min))

    # for ((x_min, y_min), (x_max, y_max)) in all_grouped_box:
    #     # print((x_min, y_min), (x_max, y_max))

    ctx._flatten(color=(0, 1, 0))

    ctx._new_render_layer()
    for i in range(len(index_span_for_primitives) - 1):
        line_index = index_span_for_primitives[i]
        begin = line_index[0]
        end = line_index[1]
        lines = all_lines_and_arc_primitives[begin:end + 1]
        if show_char:  # 显示被筛选出来的字符,false则只有bounding box

            for p in lines:
                s_x, s_y = p.start
                p.start = s_x * ratio, s_y * ratio
                e_x, e_y = p.end
                p.end = e_x * ratio, e_y * ratio

                if isinstance(p, Arc):
                    c_x, c_y = p.center
                    p.center = c_x * ratio, c_y * ratio
                ctx.render(p)
    ctx._flatten()

    filename_with_coordination = append_filename_with_coordination('{}-{}.png'.format(0, 0), bounding_box)
    image_path = os.path.join(output_dir, filename_with_coordination)
    ctx.dump(image_path)
    return filename_with_coordination
Beispiel #13
0
import gerber
from gerber.render import GerberCairoContext

# Read gerber and Excellon files
dim = gerber.read('tty.dim')

# Rendering context
ctx = GerberCairoContext()

# Create SVG image
ctx.color = (0, 1, 0)
dim.render(ctx, "tty_dim.svg")
print(ctx)

ctx.dump("foo.svg")
Beispiel #14
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.

if __name__ == '__main__':
    from gerber.common import read
    from gerber.render import GerberCairoContext
    import sys

    if len(sys.argv) < 2:
        sys.stderr.write("Usage: python -m gerber <filename> <filename>...\n")
        sys.exit(1)

    ctx = GerberCairoContext()
    ctx.alpha = 0.95
    for filename in sys.argv[1:]:
        print("parsing %s" % filename)
        if 'GTO' in filename or 'GBO' in filename:
            ctx.color = (1, 1, 1)
            ctx.alpha = 0.8
        elif 'GTS' in filename or 'GBS' in filename:
            ctx.color = (0.2, 0.2, 0.75)
            ctx.alpha = 0.8
        gerberfile = read(filename)
        gerberfile.render(ctx)

    print('Saving image to test.svg')
    ctx.dump('test.svg')
ctx.render_layer(mask)


# The default style can be overridden by passing a RenderSettings instance to
# render_layer().
# First, create a settings object:
our_settings = RenderSettings(color=theme.COLORS['white'], alpha=0.85)

# Draw the silkscreen layer, and specify the rendering settings to use
ctx.render_layer(silk, settings=our_settings)

# Draw the drill layer
ctx.render_layer(drill)

# Write output to png file
ctx.dump(os.path.join(os.path.dirname(__file__), 'cairo_example.png'))

# Load the bottom layers
copper = load_layer(os.path.join(GERBER_FOLDER, 'bottom_copper.GBL'))
mask = load_layer(os.path.join(GERBER_FOLDER, 'bottom_mask.GBS'))

# Clear the drawing
ctx.clear()

# Render bottom layers
ctx.render_layer(copper)
ctx.render_layer(mask)
ctx.render_layer(drill)

# Write png file
ctx.dump(os.path.join(os.path.dirname(__file__), 'cairo_bottom.png'))
Beispiel #16
0
# Created by mqgao at 2019/3/19
"""
Feature: #Enter feature name here
# Enter feature description here

Scenario: #Enter scenario name here
# Enter steps here

Test File Location: # Enter
"""
import gerber
import os
from gerber.render import GerberCairoContext

gm2_dir = '/Users/mqgao/PycharmProjects/auto-pcb-ii/tokenization/gerber_tokenization/data/gerbers'

for i, f in enumerate(os.listdir(gm2_dir)):
    print(i)
    gerber_obj = gerber.read(os.path.join(gm2_dir, f))

    ctx = GerberCairoContext()

    gerber_obj.render(ctx)

    ctx.dump('test-gerber-{}.png'.format(i))

    print('generate end!')
Beispiel #17
0
import os
import gerber
import sys
import json
from gerber.render import GerberCairoContext
from gerber.utils import parse_gerber_value
from gerber.rs274x import GerberParser

copper = gerber.read('input.GTL')  # argument string is the filename

# Rendering context
ctx = GerberCairoContext()

# Create PNG
copper.render(ctx)
# js = GerberParser.parse('input.GTL')
# print(js)
# # with open('data.json', 'w') as outfile:
# #     json.dump(js, outfile)

# # with open('data.json') as f:
# #     data = json.load(f)
# # print(data[0])

ctx.dump(os.path.join(os.path.dirname(__file__), 'output.png'))
#print("Saved")
exit()
Beispiel #18
0
mask = read(os.path.join(GERBER_FOLDER, 'soldermask.GTS'))
silk = read(os.path.join(GERBER_FOLDER, 'silkscreen.GTO'))
drill = read(os.path.join(GERBER_FOLDER, 'ncdrill.DRD'))

# Create a new drawing context
ctx = GerberCairoContext()

# Draw the copper layer
copper.render(ctx)

# Set opacity and color for soldermask layer
ctx.alpha = 0.6
ctx.color = (0.2, 0.2, 0.75)

# Draw the soldermask layer
mask.render(ctx)

# Set opacity and color for silkscreen layer
ctx.alpha = 0.85
ctx.color = (1, 1, 1)

# Draw the silkscreen layer
silk.render(ctx)

# Set opacity for drill layer
ctx.alpha = 1.
drill.render(ctx)

# Write output to png file
ctx.dump(os.path.join(os.path.dirname(__file__), 'cairo_example.png'))
Beispiel #19
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.

if __name__ == '__main__':
    from gerber.common import read
    from gerber.render import GerberCairoContext
    import sys

    if len(sys.argv) < 2:
        sys.stderr.write("Usage: python -m gerber <filename> <filename>...\n")
        sys.exit(1)

    ctx = GerberCairoContext()
    ctx.alpha = 0.95
    for filename in sys.argv[1:]:
        print("parsing %s" % filename)
        if 'GTO' in filename or 'GBO' in filename:
            ctx.color = (1, 1, 1)
            ctx.alpha = 0.8
        elif 'GTS' in filename or 'GBS' in filename:
            ctx.color = (0.2, 0.2, 0.75)
            ctx.alpha = 0.8
        gerberfile = read(filename)
        gerberfile.render(ctx)

    print('Saving image to preview.svg')
    ctx.dump('preview.svg')