无法使用白色背景OpenCV在JPG中保存图像

时间:2017-02-12 11:03:13

标签: c++ opencv jpeg alpha

我在OpenCV中编写了一个简单的应用程序,删除了图像的黑色背景,并在JPG中以白色背景保存。但是,它始终以黑色背景保存。

这是我的代码:

import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { NgForm } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
  selector: 'my-app',
  template: `
            <div>
            <form #f="ngForm"> 
              <button (click)="log(name)">Click me</button>
              <input *ngIf="true" name="name" [(ngModel)]="name" />
            </form>
            </div>
          `,
})
export class App {
  name: string;
  log: string;
  constructor() {
    this.name = 'Angular2'
  }

  logMe(s) {
    this.log = s;
  }
}

@NgModule({
  imports: [BrowserModule, FormsModule, CommonModule],
  declarations: [App],
  bootstrap: [App]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:1)

您只需使用带掩码的setTo根据掩码将某些像素设置为特定值:

Mat src = imread("../temp/temp1.jpg",1) ;
Mat dst;
Mat gray, thr;

cvtColor(src, gray, COLOR_BGR2GRAY);

// Are you sure to use 0 as threshold value?
threshold(gray, thr, 0, 255, THRESH_BINARY);

// Clone src into dst
dst = src.clone();

// Set to white all pixels that are not zero in the mask
dst.setTo(Scalar(255,255,255) /*white*/, thr);

imwrite("../temp/r5.jpg", dst);

还有一些注意事项:

  1. 您可以使用以下方式直接将图像加载为灰度:imread(..., IMREAD_GRAYSCALE);

  2. 您可以避免使用所有临时Mat s。

  3. 您确定要使用0作为阈值吗?因为在这种情况下,您可以完全避免应用theshold,并将灰度图像中所有0像素设置为白色:dst.setTo(Scalar(255,255,255), gray == 0);
  4. 我就是这样做的:

    // Load the image 
    Mat src = imread("path/to/img", IMREAD_COLOR);
    
    // Convert to grayscale
    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY); 
    
    // Set to white all pixels that are 0 in the grayscale image
    src.setTo(Scalar(255,255,255), gray == 0)
    
    // Save
    imwrite("path/to/other/img", src);