用颜色填充图像表面的任何方法? (Canvas)的

时间:2018-03-07 16:15:31

标签: html5 canvas

我正在寻找一种用帆布颜色填充图像表面的方法,但却找不到我正在寻找的东西。

有没有办法做到这一点?

有一个我正在谈论的例子:

如果图像是这样的:

enter image description here

我需要用画布绘制它:

enter image description here

只需用颜色填充实际图像表面(在这种情况下为黑色)。

我认为这个Android方法也是如此,所以我希望画布上有类似的内容。

imageView.setColorFilter(Color.RED);

提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用合成模式执行此操作,更具体地说,使用源代码:

import cv2
import numpy as np
from detect import detect_fist

import time

cap = cv2.VideoCapture(0)
isFist = 0
current_time = 0 
target_time = 0
first_fist_detection = False
while (cap.isOpened()):

    ret, img = cap.read()
    img = cv2.flip(img, 1)
    cv2.rectangle(img, (50, 50), (150, 150), (0, 255, 0), 0)
    confirm = img[50:150, 50:150] # narrow the whole webcam to a box 

    isFist = detect_fist(confirm) # a function to detect fist inside that box


    current_time = int(time.time())

    if isFist and not first_fist_detection:
        first_fist_detection = True
        target_time = current_time + 2
    elif isFist and first_fist_detection:
        if current_time > target_time:
            cv2.putText(img, "Fist", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2)
    else:
        #that is, no fist is detected
        first_fist_detection = False        

    cv2.imshow('Gesture', img)

    k = cv2.waitKey(10)
    if k == 27:
        break

ctx.globalCompositeOperation = "source-in";
ctx.fillRect(x, y, w, h); // fill the image area using current color
// Using the original colored logo in OPs post:
var img = new Image; img.onload = go; img.src = "//i.stack.imgur.com/kv435.png";
function go() {
  var ctx = c.getContext("2d");
  c.width = this.width; c.height = this.height;
  ctx.drawImage(this, 0, 0);
  
  // change color
  ctx.globalCompositeOperation = "source-in";
  ctx.fillRect(0, 0, c.width, c.height);      // def. color is black
}

重要的是要知道复合操作是否与alpha通道一起使用。如果图像没有alpha通道但只有白色背景,则此方法不起作用。在这种情况下,您需要迭代每个像素并将所有非白色像素替换为目标颜色像素。

对于此方法,您可以使用<canvas id=c></canvas>。但我的建议是准备图像,使其在处理之前嵌入alpha通道。

相关问题